-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
69 lines (57 loc) · 1.19 KB
/
example_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
58
59
60
61
62
63
64
65
66
67
68
69
package mid
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"strings"
)
func ExampleJSON() {
type (
inType struct {
Referer bool `json:"referer"`
UserAgent bool `json:"user_agent"`
}
outType struct {
Referer string `json:"referer"`
UserAgent string `json:"user_agent"`
}
)
handler := func(ctx context.Context, in inType) (outType, error) {
var (
req = Request(ctx)
out outType
)
if in.Referer {
out.Referer = req.Referer()
}
if in.UserAgent {
out.UserAgent = req.UserAgent()
}
return out, nil
}
s := httptest.NewServer(JSON(handler))
defer s.Close()
inp := `{"user_agent":true}`
req, err := http.NewRequest("POST", s.URL, strings.NewReader(inp))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "ExampleJSON-agent/1.0")
var c http.Client
resp, err := c.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
var out outType
err = json.NewDecoder(resp.Body).Decode(&out)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Server got user agent %s\n", out.UserAgent)
// Output: Server got user agent ExampleJSON-agent/1.0
}