-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
172 lines (138 loc) · 3.67 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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package nile
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"time"
)
// Router is the basic foundation of the HTTP server.
type Router interface {
// GET adds a GET request for the matching path that executes the corresponding
// HandlerFunc upon a match.
GET(path string, fn HandlerFunc) error
// POST adds a POST request for the matching path that executes the
// corresponding HandlerFunc upon a match.
POST(path string, fn HandlerFunc) error
// PATCH adds a PATCH request for the matching path that executes the
// corresponding HandlerFunc upon a match.
PATCH(path string, fn HandlerFunc) error
// PUT adds a PUT request for the matching path that executes the corresponding
// HandlerFunc upon a match.
PUT(path string, fn HandlerFunc) error
// DELETE adds a DELETE request for the matching path that executes the
// corresponding HandlerFunc upon a match.
DELETE(path string, fn HandlerFunc) error
// Start initializes the router.
Start(addr string) error
}
type router struct {
segments map[string]*segment
}
// New creates a new Router instance.
func New() Router {
return &router{
segments: map[string]*segment{},
}
}
func (r *router) Start(addr string) error {
server := &http.Server{
Addr: addr,
Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
printLogo(addr)
return server.ListenAndServe()
}
func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
method := req.Method
var match *match
var hasMatch bool
for _, segment := range r.segments {
match, hasMatch = segment.Matches(path)
if hasMatch {
break
}
}
if !hasMatch {
r.writeResponse(NewResourceNotFound(), w)
return
}
endpoint, found := match.Segment.Endpoint(method)
if !found {
r.writeResponse(NewMethodNotAllowed(), w)
return
}
context := match.Context
context.setRequest(req)
handler := endpoint.Handler()
resp := handler(context)
r.writeResponse(resp, w)
}
func (r *router) writeResponse(resp Response, w http.ResponseWriter) {
respBytes, err := json.Marshal(resp.Body())
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(resp.StatusCode())
w.Write(respBytes)
}
func (r *router) GET(path string, fn HandlerFunc) error {
return r.addRoute(path, http.MethodGet, fn)
}
func (r *router) POST(path string, fn HandlerFunc) error {
return r.addRoute(path, http.MethodPost, fn)
}
func (r *router) PATCH(path string, fn HandlerFunc) error {
return r.addRoute(path, http.MethodPatch, fn)
}
func (r *router) PUT(path string, fn HandlerFunc) error {
return r.addRoute(path, http.MethodPut, fn)
}
func (r *router) DELETE(path string, fn HandlerFunc) error {
return r.addRoute(path, http.MethodDelete, fn)
}
func (r *router) addRoute(path string, method string, handler HandlerFunc) error {
seg, err := newSegmentEndpoint(path, method, handler)
if err != nil {
return err
}
existing, found := r.segments[seg.Path]
if found {
merged, err := mergeSegments(existing, seg)
if err != nil {
return err
}
r.segments[seg.Path] = merged
} else {
r.segments[seg.Path] = seg
}
return nil
}
func printLogo(addr string) {
const logo = `
(_) |
_ __ _| | ___
| '_ \| | |/ _ \
| | | | | | __/
|_| |_|_|_|\___|
`
fmt.Println(logo)
fmt.Println(formatAddress(addr))
}
func formatAddress(addr string) string {
if string(addr[0]) == ":" {
// Assume this means we start with the port.
addr = "http://localhost" + addr
}
url, err := url.Parse(addr)
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("Server started on: %s", url.String())
}