blob: 92c1a2395efd83fb591ee9b0f551eb9f9cc4b23a (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
# API wrapper
API handler wrapper
## 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/neonxp/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"`
}
```
|