diff options
-rw-r--r-- | README.md | 52 | ||||
-rw-r--r-- | _examples/wrap/main.go | 4 | ||||
-rw-r--r-- | go.mod | 2 | ||||
-rw-r--r-- | handler.go | 4 |
4 files changed, 56 insertions, 6 deletions
@@ -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) @@ -1,3 +1,3 @@ -module github.com/gogeneric/web +module github.com/gogeneric/api go 1.18 @@ -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 { |