-
Notifications
You must be signed in to change notification settings - Fork 3
/
gensym_test.go
66 lines (54 loc) · 1.51 KB
/
gensym_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
// Copyright (C) 2016 JT Olds
// See LICENSE for copying information
package webhelp_test
import (
"fmt"
"net/http"
"golang.org/x/net/context"
"gopkg.in/webhelp.v1"
"gopkg.in/webhelp.v1/whcompat"
"gopkg.in/webhelp.v1/wherr"
"gopkg.in/webhelp.v1/whlog"
"gopkg.in/webhelp.v1/whroute"
)
var (
UserKey = webhelp.GenSym()
)
type User struct {
Name string
}
func loadUser(r *http.Request) (user *User, err error) {
return nil, wherr.InternalServerError.New("not implemented yet")
}
// myWrapper will load the user from a request, serving any detected errors,
// and otherwise passing the request along to the wrapped handler with the
// user bound inside the context.
func myWrapper(h http.Handler) http.Handler {
return whroute.HandlerFunc(h,
func(w http.ResponseWriter, r *http.Request) {
user, err := loadUser(r)
if err != nil {
wherr.Handle(w, r, err)
return
}
h.ServeHTTP(w, whcompat.WithContext(r,
context.WithValue(whcompat.Context(r), UserKey, user)))
})
}
// myHandler is a standard http.HandlerFunc that expects to be able to load
// a user out of the request context.
func myHandler(w http.ResponseWriter, r *http.Request) {
ctx := whcompat.Context(r)
if user, ok := ctx.Value(UserKey).(*User); ok {
// do something with the user
fmt.Fprint(w, user.Name)
}
}
// Routes returns an http.Handler. You might have a whmux.Dir or something
// in here.
func Routes() http.Handler {
return myWrapper(http.HandlerFunc(myHandler))
}
func ExampleGenSym() {
whlog.ListenAndServe(":0", Routes())
}