From d36bd3f0aa6ee962cc1a0d40bfb6a428da4ff93b Mon Sep 17 00:00:00 2001 From: Alexander Kiryukhin Date: Sun, 19 Dec 2021 20:14:07 +0300 Subject: [PATCH] Fix readme and example --- README.md | 52 +++++++++++++++++++++++++++++++++++++++++- _examples/wrap/main.go | 4 ++-- go.mod | 2 +- handler.go | 4 ++-- 4 files changed, 56 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index ba31628..7540e8e 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,52 @@ -# api +# API Generic api functions + +## Usage + +### api.Wrap(handler) + +Function Wrap wraps API handler and returns standard http.HandlerFunc. It encapsulate body parsing. + +#### Example + +```go +package main + +import ( + "context" + "fmt" + "log" + "net/http" + + "github.com/gogeneric/api" +) + +func main() { + h := &http.Server{Addr: "0.0.0.0:3000"} + mux := http.NewServeMux() + h.Handler = mux + + // Here is magic! + mux.Handle("/hello", api.Wrap(handleHello)) + + if err := h.ListenAndServe(); err != http.ErrServerClosed { + log.Fatalln(err) + } +} + +// Our API handler with custom request and response types +func handleHello(ctx context.Context, req *helloRequest) (*helloResponse, error) { + return &helloResponse{Message: fmt.Sprintf("Hello, %s!", req.Name)}, nil +} + +// Custom request type +type helloRequest struct { + Name string `json:"name"` +} + +// Custom response type +type helloResponse struct { + Message string `json:"message"` +} + +``` \ No newline at end of file diff --git a/_examples/wrap/main.go b/_examples/wrap/main.go index 42e959e..2248038 100644 --- a/_examples/wrap/main.go +++ b/_examples/wrap/main.go @@ -6,7 +6,7 @@ import ( "log" "net/http" - "github.com/gogeneric/web" + "github.com/gogeneric/api" ) func main() { @@ -15,7 +15,7 @@ func main() { h.Handler = mux // Here is magic! - mux.HandleFunc("/hello", api.Wrap(handleHello)) + mux.Handle("/hello", api.Wrap(handleHello)) if err := h.ListenAndServe(); err != http.ErrServerClosed { log.Fatalln(err) diff --git a/go.mod b/go.mod index 22545d3..0e94dca 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module github.com/gogeneric/web +module github.com/gogeneric/api go 1.18 diff --git a/handler.go b/handler.go index d497b24..62ca233 100644 --- a/handler.go +++ b/handler.go @@ -7,8 +7,8 @@ import ( "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) { +//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) if err := json.NewDecoder(r.Body).Decode(req); err != nil {