summaryrefslogtreecommitdiff
path: root/wrap_test.go
blob: 31b831ed88aaa7aefea39bda04a2eb65c51c06dd (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
package muxtool

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
)

func ExampleWrap() {
	rr := httptest.NewRecorder()

	// Sample request
	req := reqHello{
		Name: "NeonXP",
	}
	b, _ := json.Marshal(req)
	request, _ := http.NewRequest(http.MethodPost, "/hello", bytes.NewReader(b))

	// Handler
	mux := http.NewServeMux()
	// Handle wrapped `handleHello(context.Context, *reqHello) (*respHello, error)`
	mux.Handle("POST /hello", Wrap(handleHello))

	mux.ServeHTTP(rr, request)

	fmt.Println(rr.Body.String())
	// Output: {"message":"Hello, NeonXP!"}
}

type reqHello struct {
	Name string `json:"name"`
}

type respHello struct {
	Message string `json:"message"`
}

func handleHello(ctx context.Context, req *reqHello) (*respHello, error) {
	return &respHello{
		Message: fmt.Sprintf("Hello, %s!", req.Name),
	}, nil
}