Fix readme and example

This commit is contained in:
Alexander Kiryukhin 2021-12-19 20:14:07 +03:00
parent 6f5bb85330
commit d36bd3f0aa
No known key found for this signature in database
GPG key ID: 6DF7A2910D0699E9
4 changed files with 56 additions and 6 deletions

View file

@ -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"`
}
```

View file

@ -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)

2
go.mod
View file

@ -1,3 +1,3 @@
module github.com/gogeneric/web
module github.com/gogeneric/api
go 1.18

View file

@ -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 {