-
Notifications
You must be signed in to change notification settings - Fork 6
/
example_handlers_test.go
57 lines (50 loc) · 1.13 KB
/
example_handlers_test.go
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
54
55
56
57
package httprequest_test
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"github.com/julienschmidt/httprouter"
"gopkg.in/httprequest.v1"
)
type arithHandler struct {
}
type number struct {
N int
}
func (arithHandler) Add(arg *struct {
httprequest.Route `httprequest:"GET /:A/add/:B"`
A int `httprequest:",path"`
B int `httprequest:",path"`
}) (number, error) {
return number{
N: arg.A + arg.B,
}, nil
}
func ExampleServer_Handlers() {
f := func(p httprequest.Params) (arithHandler, context.Context, error) {
fmt.Printf("handle %s %s\n", p.Request.Method, p.Request.URL)
return arithHandler{}, p.Context, nil
}
router := httprouter.New()
var reqSrv httprequest.Server
for _, h := range reqSrv.Handlers(f) {
router.Handle(h.Method, h.Path, h.Handle)
}
srv := httptest.NewServer(router)
resp, err := http.Get(srv.URL + "/123/add/11")
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
panic("status " + resp.Status)
}
fmt.Println("result:")
io.Copy(os.Stdout, resp.Body)
// Output: handle GET /123/add/11
// result:
// {"N":134}
}