Repository navigation
Expand file tree
/
Copy pathreadme_test.go
More file actions
74 lines (61 loc) · 1.49 KB
/
Copy pathreadme_test.go
File metadata and controls
74 lines (61 loc) · 1.49 KB
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
72
73
74
package api_test
import (
"regexp"
"testing"
"github.com/ohait/forego/api"
"github.com/ohait/forego/ctx"
"github.com/ohait/forego/http"
"github.com/ohait/forego/test"
)
type WordFilter struct {
Blacklist *regexp.Regexp
In string `api:"in,required" json:"in"`
Out string `api:"out" json:"out"`
Count int `api:"out" json:"count"`
}
func (wf *WordFilter) Do(c ctx.C) error {
wf.Out = wf.Blacklist.ReplaceAllStringFunc(wf.In, func(bad string) string {
wf.Count++
return "***"
})
return nil
}
func TestWordFilter(t *testing.T) {
c := test.Context(t)
re := regexp.MustCompile(`(bad|worse|worst)`)
out := api.Test(c, &WordFilter{
Blacklist: re,
In: "ok, bad or worse",
})
test.EqualsStr(t, "ok, *** or ***", out.Out)
test.EqualsGo(t, 2, out.Count)
}
func exampleWordFilter(c ctx.C) { // nolint
s := http.NewServer(c)
_, _ = s.RegisterAPI(c, "/wc", &WordFilter{
Blacklist: regexp.MustCompile(`(foo|bar)`), // this will be copied by ref for each request
})
}
func exampleHandler(c ctx.C) error { // nolint
h, err := api.NewHandler(c, &WordFilter{})
if err != nil {
return err
}
ser := h.Server()
onRequest := func(c ctx.C, req api.ServerRequest, res api.ServerResponse) error {
// un marshal the request into a new *WordFilter
op, err := ser.Recv(c, req)
if err != nil {
return err
}
// call *WordFilter.Do()
err = op.Do(c)
if err != nil {
return err
}
// marshal back the response
return ser.Send(c, op, res)
}
_ = onRequest
return nil
}