diff options
author | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2022-01-05 21:21:51 +0300 |
---|---|---|
committer | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2022-01-05 21:21:51 +0300 |
commit | b3c48f806724b82b649c89aa5e0d07a09e414140 (patch) | |
tree | 61b5925b2a25c74d1966b757be23168a2663a227 /wrap.go | |
parent | d36bd3f0aa6ee962cc1a0d40bfb6a428da4ff93b (diff) |
Added interfaces
Diffstat (limited to 'wrap.go')
-rw-r--r-- | wrap.go | 51 |
1 files changed, 51 insertions, 0 deletions
@@ -0,0 +1,51 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" +) + +//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 { + return func(w http.ResponseWriter, r *http.Request) { + req := new(RQ) + 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 + } + } + resp, err := handler(r.Context(), req) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(err.Error())) + return + } + if err := json.NewEncoder(w).Encode(resp); err != nil { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(err.Error())) + return + } + } +} + +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) + } +} + +type WithHeader interface { + WithHeader(header http.Header) +} + +type WithMethod interface { + WithMethod(method string) +} |