aboutsummaryrefslogtreecommitdiffstats
path: root/http/router.go
blob: e7087f7ce85e8d2e38dea06bb1cdfabb07717d2d (plain) (blame)
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
package http

import (
	"encoding/json"
	"net/http"
)

type router struct {
	routes []*route
}

type route struct {
	method  string
	path    string
	handler appHandler
}

type appHandler func(http.ResponseWriter, *http.Request) (interface{}, *httpError)

func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	data, e := fn(w, r)
	w.Header().Set("Content-Type", "application/json")
	if e != nil { // e is *Error, not os.Error.
		if e.Message == "" {
			e.Message = e.err.Error()
		}
		out, err := json.Marshal(e)
		if err != nil {
			panic(err)
		}
		w.WriteHeader(e.Status)
		w.Write(out)
	} else if data != nil {
		out, err := json.Marshal(data)
		if err != nil {
			panic(err)
		}
		w.Write(out)
	}
}

func newRouter() *router { return &router{} }

func notFoundHandler(w http.ResponseWriter, r *http.Request) (interface{}, *httpError) {
	return nil, &httpError{
		Status:  http.StatusNotFound,
		Message: "Resource not found",
	}
}

func (r *router) route(method, path string, handler appHandler) *route {
	route := route{
		method:  method,
		path:    path,
		handler: handler,
	}
	r.routes = append(r.routes, &route)
	return &route
}

func (r *router) handler() http.Handler {
	return appHandler(func(w http.ResponseWriter, req *http.Request) (interface{}, *httpError) {
		for _, route := range r.routes {
			if route.match(req) {
				return route.handler(w, req)
			}
		}
		return notFoundHandler(w, req)
	})
}

func (r *route) match(req *http.Request) bool {
	if req.Method != r.method {
		return false
	}
	if r.path != req.URL.Path {
		return false
	}
	return true
}