-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathexample_middleware_test.go
57 lines (45 loc) · 1.12 KB
/
example_middleware_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
package ctxdata_test
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/peterbourgon/ctxdata/v4"
)
type Server struct{}
func NewServer() *Server {
return &Server{}
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
d := ctxdata.From(r.Context())
d.Set("method", r.Method)
d.Set("path", r.URL.Path)
d.Set("content_length", r.ContentLength)
fmt.Fprintln(w, "OK")
}
type Middleware struct {
next http.Handler
}
func NewMiddleware(next http.Handler) *Middleware {
return &Middleware{next: next}
}
func (mw *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx, d := ctxdata.New(r.Context())
defer func() {
for _, kv := range d.GetAllSlice() {
fmt.Printf("%s: %v\n", kv.Key, kv.Val)
}
}()
mw.next.ServeHTTP(w, r.WithContext(ctx))
}
func Example_middleware() {
server := NewServer()
middleware := NewMiddleware(server)
testserver := httptest.NewServer(middleware)
defer testserver.Close()
http.Post(testserver.URL+"/path", "text/plain; charset=utf-8", strings.NewReader("hello world"))
// Output:
// method: POST
// path: /path
// content_length: 11
}