diff options
author | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2021-12-19 20:08:05 +0300 |
---|---|---|
committer | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2021-12-19 20:08:05 +0300 |
commit | 6f5bb85330acd4227d4c233e283f384e6ff834c8 (patch) | |
tree | b997176261bc5df75449ec687c299d8828f15e5e | |
parent | 55a7b7d61484d5fe374a1093f328de1cc775b0b6 (diff) |
Initial
-rw-r--r-- | _examples/wrap/main.go | 35 | ||||
-rw-r--r-- | _examples/wrap/test.http | 12 | ||||
-rw-r--r-- | go.mod | 3 | ||||
-rw-r--r-- | handler.go | 31 |
4 files changed, 81 insertions, 0 deletions
diff --git a/_examples/wrap/main.go b/_examples/wrap/main.go new file mode 100644 index 0000000..42e959e --- /dev/null +++ b/_examples/wrap/main.go @@ -0,0 +1,35 @@ +package main + +import ( + "context" + "fmt" + "log" + "net/http" + + "github.com/gogeneric/web" +) + +func main() { + h := &http.Server{Addr: "0.0.0.0:3000"} + mux := http.NewServeMux() + h.Handler = mux + + // Here is magic! + mux.HandleFunc("/hello", api.Wrap(handleHello)) + + if err := h.ListenAndServe(); err != http.ErrServerClosed { + log.Fatalln(err) + } +} + +func handleHello(ctx context.Context, req *helloRequest) (*helloResponse, error) { + return &helloResponse{Message: fmt.Sprintf("Hello, %s!", req.Name)}, nil +} + +type helloRequest struct { + Name string `json:"name"` +} + +type helloResponse struct { + Message string `json:"message"` +} diff --git a/_examples/wrap/test.http b/_examples/wrap/test.http new file mode 100644 index 0000000..fd8230c --- /dev/null +++ b/_examples/wrap/test.http @@ -0,0 +1,12 @@ +### Request: +http://localhost:3000/hello +Content-Type: application/json + +{ + "name": "Alex" +} + +### Response: +# http://localhost:3000/hello +# +#{"message":"Hello, Alex!"} @@ -0,0 +1,3 @@ +module github.com/gogeneric/web + +go 1.18 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 + } + } +} |