forked from goadesign/goa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmux.go
197 lines (177 loc) · 6.36 KB
/
mux.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package goa
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"github.com/julienschmidt/httprouter"
"github.com/raphael/goa/design"
)
type (
// ServeMux is the interface implemented by the goa HTTP request mux. The goa package
// provides a default implementation with DefaultMux.
//
// The goa mux allows for routing to controllers serving different API versions. Each
// version has is own mux accessed via Version. Upon receving a HTTP request the ServeMux
// ServeHTTP method looks up the targetted API version and dispatches the request to the
// corresponding mux.
ServeMux interface {
VersionMux
// Version returns the mux for the given API version.
Version(version string) VersionMux
// HandleMissingVersion handles requests that specify a non-existing API version.
HandleMissingVersion(rw http.ResponseWriter, req *http.Request, version string)
}
// VersionMux is the interface implemented by API version specific request mux.
// It implements http.Handler and makes it possible to register request handlers for
// specific HTTP methods and request path via the Handle method.
VersionMux interface {
http.Handler
// Handle sets the HandleFunc for a given HTTP method and path.
Handle(method, path string, handle HandleFunc)
// Lookup returns the HandleFunc associated with the given HTTP method and path.
Lookup(method, path string) HandleFunc
}
// HandleFunc provides the implementation for an API endpoint.
// The values include both the querystring and path parameter values.
HandleFunc func(http.ResponseWriter, *http.Request, url.Values)
// DefaultMux is the default goa mux. It dispatches requests to the appropriate version mux
// using a SelectVersionFunc. The default func is DefaultVersionFunc, change it with
// SelectVersion.
DefaultMux struct {
*defaultVersionMux
selectVersion SelectVersionFunc
muxes map[string]VersionMux
}
// SelectVersionFunc is used by the default goa mux to compute the API version targetted by
// a given request.
// The default implementation looks for a version as path prefix.
// Alternate implementations can be set using the DefaultMux SelectVersion method.
SelectVersionFunc func(*http.Request) string
// defaultVersionMux is the default goa API version specific mux.
defaultVersionMux struct {
router *httprouter.Router
handles map[string]HandleFunc
}
)
// NewMux creates a top level mux using the default goa mux implementation.
func NewMux() ServeMux {
return &DefaultMux{
defaultVersionMux: &defaultVersionMux{
router: httprouter.New(),
handles: make(map[string]HandleFunc),
},
selectVersion: PathSelectVersionFunc("/:version"),
}
}
// PathSelectVersionFunc returns a SelectVersionFunc that uses the given path pattern to extract the
// version from the request path. Use the same path pattern given in the DSL to define the API base
// path, e.g. "/api/:version".
func PathSelectVersionFunc(pattern string) SelectVersionFunc {
rgs := design.WildcardRegex.ReplaceAllLiteralString(pattern, `([^/]+)`)
rg := regexp.MustCompile("^" + rgs)
return func(req *http.Request) (version string) {
match := rg.FindStringSubmatch(req.URL.Path)
if len(match) > 1 {
version = match[1]
}
return
}
}
// HeaderSelectVersionFunc returns a SelectVersionFunc that looks for the version in the header with
// the given name.
func HeaderSelectVersionFunc(header string) SelectVersionFunc {
return func(req *http.Request) string {
return req.Header.Get(header)
}
}
// QuerySelectVersionFunc returns a SelectVersionFunc that looks for the version in the querystring
// with the given key.
func QuerySelectVersionFunc(query string) SelectVersionFunc {
return func(req *http.Request) string {
return req.URL.Query().Get(query)
}
}
// CombineSelectVersionFunc returns a SelectVersionFunc that tries each func passed as argument
// in order and returns the first non-empty string version.
func CombineSelectVersionFunc(funcs ...SelectVersionFunc) SelectVersionFunc {
return func(req *http.Request) string {
for _, f := range funcs {
if version := f(req); version != "" {
return version
}
}
return ""
}
}
// Version returns the mux addressing the given version if any.
func (m *DefaultMux) Version(version string) VersionMux {
if m.muxes == nil {
m.muxes = make(map[string]VersionMux)
}
if mux, ok := m.muxes[version]; ok {
return mux
}
mux := &defaultVersionMux{
router: httprouter.New(),
handles: make(map[string]HandleFunc),
}
m.muxes[version] = mux
return mux
}
// SelectVersion sets the func used to compute the API version targetted by a request.
func (m *DefaultMux) SelectVersion(sv SelectVersionFunc) {
m.selectVersion = sv
}
// HandleMissingVersion handles requests that specify a non-existing API version.
func (m *DefaultMux) HandleMissingVersion(rw http.ResponseWriter, req *http.Request, version string) {
rw.WriteHeader(400)
resp := TypedError{ID: ErrInvalidVersion, Mesg: fmt.Sprintf(`API does not support version %s`, version)}
b, err := json.Marshal(resp)
if err != nil {
b = []byte("API does not support version")
}
rw.Write(b)
}
// ServeHTTP is the function called back by the underlying HTTP server to handle incoming requests.
func (m *DefaultMux) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Optimize the unversionned API case
if len(m.muxes) == 0 {
m.router.ServeHTTP(rw, req)
return
}
var mux VersionMux
version := m.selectVersion(req)
if version == "" {
mux = m.defaultVersionMux
} else {
var ok bool
mux, ok = m.muxes[version]
if !ok {
m.HandleMissingVersion(rw, req, version)
return
}
}
mux.ServeHTTP(rw, req)
}
// Handle sets the handler for the given verb and path.
func (m *defaultVersionMux) Handle(method, path string, handle HandleFunc) {
hthandle := func(rw http.ResponseWriter, req *http.Request, htparams httprouter.Params) {
params := req.URL.Query()
for _, p := range htparams {
params.Set(p.Key, p.Value)
}
handle(rw, req, params)
}
m.handles[method+path] = handle
m.router.Handle(method, path, hthandle)
}
// Lookup returns the HandleFunc associated with the given method and path.
func (m *defaultVersionMux) Lookup(method, path string) HandleFunc {
return m.handles[method+path]
}
// ServeHTTP is the function called back by the underlying HTTP server to handle incoming requests.
func (m *defaultVersionMux) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
m.router.ServeHTTP(rw, req)
}