-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
42 lines (34 loc) · 810 Bytes
/
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
package main
import (
"fmt"
"net/http"
)
type Router struct {
routes []*Route
}
func NewRouter() *Router {
router := &Router{}
routes := loadRoutes()
for _, route := range routes {
router.AddRoute(&route)
}
return router
}
func (r *Router) AddRoute(route *Route) {
r.routes = append(r.routes, route)
}
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
for _, route := range r.routes {
if route.Path == req.URL.Path {
r.makeRedirect(rw, req, route)
fmt.Printf("action=matched path=%s dest=%s\n", route.Path, route.Dest)
return
}
}
// no path matched; send 404 response
http.NotFound(rw, req)
}
func (r *Router) makeRedirect(rw http.ResponseWriter, req *http.Request, route *Route) {
http.Redirect(rw, req, route.Dest, 302)
go incRouteCounter(route)
}