-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve.go
105 lines (81 loc) · 2.12 KB
/
serve.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package mohttp
import (
"github.com/julienschmidt/httprouter"
"golang.org/x/net/context"
"net/http"
"sort"
)
func prio(h Handler) int {
if ph, ok := h.(PriorityHandler); ok {
return ph.Priority()
}
return 0
}
type sortedHandlers []Handler
func (s sortedHandlers) Len() int { return len(s) }
func (s sortedHandlers) Swap(a, b int) { s[a], s[b] = s[b], s[a] }
func (s sortedHandlers) Less(a, b int) bool { return prio(s[a]) < prio(s[b]) }
func Serve(c context.Context, handlers ...Handler) {
if len(handlers) == 0 {
return
}
if len(handlers) == 1 {
handlers[0].Handle(c)
return
}
var (
idx = 0
sorted = sortedHandlers(handlers)
)
sort.Stable(sorted)
next := HandlerFunc(func(c context.Context) {
if idx >= len(sorted) {
return
}
cur := sorted[idx]
idx++
cur.Handle(c)
})
c = nextStore.Set(c, next)
next(c)
}
func HTTPContext(w http.ResponseWriter, r *http.Request, p httprouter.Params) context.Context {
c := context.Background()
c = WithRequest(c, r)
c = WithResponseWriter(c, w)
c = WithPathValues(c, &PathValues{
Params: params(p),
Query: query(r.URL.Query()),
})
return c
}
var (
reqStore = NewContextValueStore("github.com/jonasi/mohttp.Request")
respStore = NewContextValueStore("github.com/jonasi/mohttp.ResponseWriter")
pathStore = NewContextValueStore("github.com/jonasi/mohttp.PathValues")
nextStore = NewContextValueStore("github.com/jonasi/mohttp.Next")
)
func WithRequest(c context.Context, r *http.Request) context.Context {
return reqStore.Set(c, r)
}
func GetRequest(c context.Context) *http.Request {
return reqStore.Get(c).(*http.Request)
}
func WithResponseWriter(c context.Context, w http.ResponseWriter) context.Context {
return respStore.Set(c, w)
}
func GetResponseWriter(c context.Context) http.ResponseWriter {
return respStore.Get(c).(http.ResponseWriter)
}
func WithPathValues(c context.Context, p *PathValues) context.Context {
return pathStore.Set(c, p)
}
func GetPathValues(c context.Context) *PathValues {
return pathStore.Get(c).(*PathValues)
}
func Next(c context.Context) {
h, ok := nextStore.Get(c).(HandlerFunc)
if ok {
h(c)
}
}