From 6f5bb85330acd4227d4c233e283f384e6ff834c8 Mon Sep 17 00:00:00 2001 From: Alexander Kiryukhin Date: Sun, 19 Dec 2021 20:08:05 +0300 Subject: Initial --- handler.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 handler.go (limited to 'handler.go') diff --git a/handler.go b/handler.go new file mode 100644 index 0000000..d497b24 --- /dev/null +++ b/handler.go @@ -0,0 +1,31 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "net/http" +) + +//Wrap API handler and returns standard http handler function +func Wrap[RQ any, RS any](handler func(ctx context.Context, request *RQ) (RS, error)) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + req := new(RQ) + if err := json.NewDecoder(r.Body).Decode(req); err != nil { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(fmt.Sprintf("Fail to parse request body: %s", 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 + } + } +} -- cgit v1.2.3