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
70
71
|
package http
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
func ExampleServer_customHTTPStatusCode() {
type CustomResponse struct {
Status int `json:"status"`
}
exp := CustomResponse{
Status: http.StatusBadRequest,
}
opts := &ServerOptions{
Address: "127.0.0.1:8123",
}
testServer, err := NewServer(opts)
if err != nil {
log.Fatal(err)
}
go func() {
err = testServer.Start()
if err != nil {
log.Println(err)
}
}()
defer func() {
_ = testServer.Stop(5 * time.Second)
}()
epCustom := &Endpoint{
Path: "/error/custom",
RequestType: RequestTypeJSON,
ResponseType: ResponseTypeJSON,
Call: func(res http.ResponseWriter, req *http.Request, reqBody []byte) (
resbody []byte, err error,
) {
res.WriteHeader(exp.Status)
return json.Marshal(exp)
},
}
err = testServer.registerPost(epCustom)
if err != nil {
log.Fatal(err)
}
// Wait for the server fully started.
time.Sleep(1 * time.Second)
client := NewClient("http://127.0.0.1:8123", nil, false)
httpRes, resBody, err := client.PostJSON(nil, epCustom.Path, nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%d\n", httpRes.StatusCode)
fmt.Printf("%s\n", resBody)
// Output:
// 400
// {"status":400}
}
|