-
Notifications
You must be signed in to change notification settings - Fork 1
/
hrt_example_get_test.go
53 lines (42 loc) · 1.15 KB
/
hrt_example_get_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
package hrt_test
import (
"context"
"fmt"
"net/url"
"strings"
"github.com/pkg/errors"
"libdb.so/hrt/v2"
"libdb.so/hrt/v2/internal/ht"
)
// EchoRequest is a simple request type that echoes the request.
type EchoRequest struct {
What string `query:"what"`
}
// Validate implements the hrt.Validator interface.
func (r EchoRequest) Validate() error {
if !strings.HasSuffix(r.What, "!") {
return errors.New("enthusiasm required")
}
return nil
}
// EchoResponse is a simple response that follows after EchoRequest.
type EchoResponse struct {
What string `json:"what"`
}
func handleEcho(ctx context.Context, req EchoRequest) (EchoResponse, error) {
return EchoResponse{What: req.What}, nil
}
func Example_get() {
r := hrt.NewRouter()
r.Use(hrt.Use(hrt.DefaultOpts))
r.Get("/echo", hrt.Wrap(handleEcho))
srv := ht.NewServer(r)
defer srv.Close()
resp := srv.MustGet("/echo", url.Values{"what": {"hi"}})
fmt.Printf("HTTP %d: %s", resp.Status, resp.Body)
resp = srv.MustGet("/echo", url.Values{"what": {"hi!"}})
fmt.Printf("HTTP %d: %s", resp.Status, resp.Body)
// Output:
// HTTP 400: {"error":"400: enthusiasm required"}
// HTTP 200: {"what":"hi!"}
}