aboutsummaryrefslogtreecommitdiffstats
path: root/http/router.go
blob: 2e6b77b1e97478eaadf45a8668fec38aa867c012 (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
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) *httpError

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

func notFoundHandler(w http.ResponseWriter, r *http.Request) *httpError {
	writeJSONHeader(w)
	return &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) *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
}