File: example_handlers_test.go

package info (click to toggle)
golang-gopkg-httprequest.v1 0.0~git20171212.fdaf1bf-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 316 kB
  • sloc: makefile: 4
file content (68 lines) | stat: -rw-r--r-- 1,418 bytes parent folder | download
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
58
59
60
61
62
63
64
65
66
67
68
package httprequest_test

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"

	"github.com/julienschmidt/httprouter"
	"golang.org/x/net/context"

	"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()
	for _, h := range exampleServer.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}
}

type exampleErrorResponse struct {
	Message string
}

var exampleServer = httprequest.Server{
	ErrorMapper: func(ctx context.Context, err error) (int, interface{}) {
		return http.StatusInternalServerError, &exampleErrorResponse{
			Message: err.Error(),
		}
	},
}