-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdirector.go
67 lines (57 loc) · 1.62 KB
/
director.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
package router
import (
"github.com/golobby/router/pkg/response"
"log"
"net/http"
"net/url"
)
// director is the base HTTP handler.
// It receives the request, and the responseWriter objects then pass them to the Route through the middlewares.
type director struct {
repository *repository
notFoundHandler Handler
}
// ServeHTTP serves HTTP requests and uses other modules to handle them.
func (d *director) ServeHTTP(rw http.ResponseWriter, request *http.Request) {
c := &DefaultContext{
repository: d.repository,
request: request,
rw: rw,
}
uri, err := url.ParseRequestURI(request.RequestURI)
if err != nil {
d.serveNotFoundError(c)
return
}
route, parameters := d.repository.findByRequest(request.Method, uri.Path)
if route == nil {
d.serveNotFoundError(c)
return
}
c.route = route
c.parameters = parameters
if err = route.stack[len(route.stack)-1](c); err != nil {
d.serveInternalError(c, err)
}
}
// serveInternalError handles internal errors.
func (d *director) serveInternalError(c Context, err error) {
log.Println("router: uncaught error=" + err.Error())
_ = c.JSON(http.StatusInternalServerError, response.M{"message": "Internal error."})
}
// serveNotFoundError handles 404 errors.
func (d *director) serveNotFoundError(c Context) {
err := d.notFoundHandler(c)
if err != nil {
d.serveInternalError(c, err)
}
}
// newDirector creates a new director instance.
func newDirector(repository *repository) *director {
return &director{
repository: repository,
notFoundHandler: func(c Context) error {
return c.JSON(http.StatusNotFound, response.M{"message": "Not found."})
},
}
}