-
Notifications
You must be signed in to change notification settings - Fork 8
/
router.go
49 lines (41 loc) · 1.13 KB
/
router.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
package rata
import (
"fmt"
"net/http"
"strings"
"github.com/bmizerany/pat"
)
// Supported HTTP methods.
const (
GET = "GET"
HEAD = "HEAD"
POST = "POST"
PUT = "PUT"
PATCH = "PATCH"
DELETE = "DELETE"
CONNECT = "CONNECT"
OPTIONS = "OPTIONS"
TRACE = "TRACE"
)
// Handlers map route names to http.Handler objects. Each Handler key must
// match a route Name in the Routes collection.
type Handlers map[string]http.Handler
// NewRouter combines a set of Routes with their corresponding Handlers to
// produce a http request multiplexer (AKA a "router"). If any route does
// not have a matching handler, an error occurs.
func NewRouter(routes Routes, handlers Handlers) (http.Handler, error) {
p := pat.New()
for _, route := range routes {
handler, ok := handlers[route.Name]
if !ok {
return nil, fmt.Errorf("missing handler %s", route.Name)
}
switch method := strings.ToUpper(route.Method); method {
case GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS, TRACE:
p.Add(method, route.Path, handler)
default:
return nil, fmt.Errorf("invalid verb: %s", route.Method)
}
}
return p, nil
}