2021-12-19 20:08:05 +03:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2021-12-19 20:14:07 +03:00
|
|
|
//Wrap API handler and returns standard http.HandlerFunc function
|
|
|
|
func Wrap[RQ any, RS any](handler func(ctx context.Context, request *RQ) (RS, error)) http.HandlerFunc {
|
2021-12-19 20:08:05 +03:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
req := new(RQ)
|
2022-01-05 21:21:51 +03:00
|
|
|
richifyRequest(req, r)
|
|
|
|
switch r.Method {
|
|
|
|
case http.MethodPost, http.MethodPatch, http.MethodDelete, http.MethodPut:
|
|
|
|
if err := json.NewDecoder(r.Body).Decode(req); err != nil {
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
_, _ = w.Write([]byte(err.Error()))
|
|
|
|
return
|
|
|
|
}
|
2021-12-19 20:08:05 +03:00
|
|
|
}
|
|
|
|
resp, err := handler(r.Context(), req)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
_, _ = w.Write([]byte(err.Error()))
|
|
|
|
return
|
|
|
|
}
|
2022-01-09 08:03:03 +03:00
|
|
|
|
|
|
|
statusCode := http.StatusOK
|
|
|
|
contentType := "application/json"
|
|
|
|
var body []byte
|
|
|
|
|
|
|
|
if v, ok := (any)(resp).(WithContentType); ok {
|
|
|
|
contentType = v.ContentType()
|
|
|
|
}
|
|
|
|
if v, ok := (any)(resp).(WithHTTPStatus); ok {
|
|
|
|
statusCode = v.Status()
|
|
|
|
}
|
|
|
|
if v, ok := (any)(resp).(Renderer); ok {
|
|
|
|
body, err = v.Render()
|
|
|
|
} else {
|
|
|
|
body, err = json.Marshal(resp)
|
|
|
|
}
|
|
|
|
if err != nil {
|
2021-12-19 20:08:05 +03:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
_, _ = w.Write([]byte(err.Error()))
|
|
|
|
return
|
|
|
|
}
|
2022-01-09 08:03:03 +03:00
|
|
|
w.WriteHeader(statusCode)
|
|
|
|
w.Header().Set("Content-Type", contentType)
|
|
|
|
w.Write(body)
|
2021-12-19 20:08:05 +03:00
|
|
|
}
|
|
|
|
}
|
2022-01-05 21:21:51 +03:00
|
|
|
|
|
|
|
func richifyRequest[RQ any](req *RQ, baseRequest *http.Request) {
|
|
|
|
if v, ok := (any)(req).(WithHeader); ok {
|
|
|
|
v.WithHeader(baseRequest.Header)
|
|
|
|
}
|
|
|
|
if v, ok := (any)(req).(WithMethod); ok {
|
|
|
|
v.WithMethod(baseRequest.Method)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-09 08:03:03 +03:00
|
|
|
type NilRequest struct{}
|