-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.go
More file actions
263 lines (231 loc) · 8.32 KB
/
router.go
File metadata and controls
263 lines (231 loc) · 8.32 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package catTrackslib
import (
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"strconv"
"time"
"unicode/utf8"
ghandlers "github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
// https://github.com/gorilla/mux#middleware
const lowerhex = "0123456789abcdef"
func appendQuoted(buf []byte, s string) []byte {
var runeTmp [utf8.UTFMax]byte
for width := 0; len(s) > 0; s = s[width:] { // nolint: wastedassign //TODO: why width starts from 0and reassigned as 1
r := rune(s[0])
width = 1
if r >= utf8.RuneSelf {
r, width = utf8.DecodeRuneInString(s)
}
if width == 1 && r == utf8.RuneError {
buf = append(buf, `\x`...)
buf = append(buf, lowerhex[s[0]>>4])
buf = append(buf, lowerhex[s[0]&0xF])
continue
}
if r == rune('"') || r == '\\' { // always backslashed
buf = append(buf, '\\')
buf = append(buf, byte(r))
continue
}
if strconv.IsPrint(r) {
n := utf8.EncodeRune(runeTmp[:], r)
buf = append(buf, runeTmp[:n]...)
continue
}
switch r {
case '\a':
buf = append(buf, `\a`...)
case '\b':
buf = append(buf, `\b`...)
case '\f':
buf = append(buf, `\f`...)
case '\n':
buf = append(buf, `\n`...)
case '\r':
buf = append(buf, `\r`...)
case '\t':
buf = append(buf, `\t`...)
case '\v':
buf = append(buf, `\v`...)
default:
switch {
case r < ' ':
buf = append(buf, `\x`...)
buf = append(buf, lowerhex[s[0]>>4])
buf = append(buf, lowerhex[s[0]&0xF])
case r > utf8.MaxRune:
r = 0xFFFD
fallthrough
case r < 0x10000:
buf = append(buf, `\u`...)
for s := 12; s >= 0; s -= 4 {
buf = append(buf, lowerhex[r>>uint(s)&0xF])
}
default:
buf = append(buf, `\U`...)
for s := 28; s >= 0; s -= 4 {
buf = append(buf, lowerhex[r>>uint(s)&0xF])
}
}
}
}
return buf
}
// buildCommonLogLine builds a log entry for req in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size.
func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte {
username := "-"
if url.User != nil {
if name := url.User.Username(); name != "" {
username = name
}
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
for _, v := range req.Header.Values("X-Forwarded-For") {
host += "->" + v
}
uri := req.RequestURI
// Requests using the CONNECT method over HTTP/2.0 must use
// the authority field (aka r.Host) to identify the target.
// Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
if req.ProtoMajor == 2 && req.Method == "CONNECT" {
uri = req.Host
}
if uri == "" {
uri = url.RequestURI()
}
buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2)
buf = append(buf, host...)
buf = append(buf, " - "...)
buf = append(buf, username...)
buf = append(buf, " ["...)
buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...)
buf = append(buf, `] "`...)
buf = append(buf, req.Method...)
buf = append(buf, " "...)
buf = appendQuoted(buf, uri)
buf = append(buf, " "...)
buf = append(buf, req.Proto...)
buf = append(buf, `" `...)
buf = append(buf, strconv.Itoa(status)...)
buf = append(buf, " "...)
buf = append(buf, strconv.Itoa(size)...)
return buf
}
// writeLog writes a log entry for req to w in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size.
func writeLog(writer io.Writer, params ghandlers.LogFormatterParams) {
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
buf = append(buf, '\n')
_, _ = writer.Write(buf)
}
func loggingMiddleware(next http.Handler) http.Handler {
return ghandlers.CustomLoggingHandler(os.Stdout, next, writeLog)
// return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// // Do stuff here
// dump, _ := httputil.DumpRequest(r, false)
// log.Println(string(dump))
//
// // Call the next handler, which can be another middleware in the chain, or the final handler.
// next.ServeHTTP(w, r)
// })
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
func contentTypeMiddlewareFor(contentType string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
w.Header().Set("Content-Type", contentType)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
}
func tokenAuthenticationMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
validToken := os.Getenv("COTOKEN")
if validToken == "" {
log.Printf("WARN: No COTOKEN set, allowing all requests")
next.ServeHTTP(w, r)
return
}
token := r.Header.Get("AuthorizationOfCats")
if token == "" {
// Header token not set. Check alternate protocol, which is using a query param with the name api_token.
// eg. catonmap.info:3001/populate/?api_token=asdfasdfb
r.ParseForm()
token = r.FormValue("api_token")
}
// Enforce token validation.
if token != validToken {
log.Println("Invalid token",
"token:", token, "validToken:", "***REDACTED***",
"method:", r.Method, "url:", r.URL, "proto:", r.Proto,
"host:", r.Host, "remote-addr:", r.RemoteAddr,
"request-URI:", r.RequestURI, "content-length:", r.ContentLength,
"user-agent:", r.UserAgent())
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
// Pass down the request to the next middleware (or final handler)
next.ServeHTTP(w, r)
})
}
type RouterOpts struct {
DisableWebsocket bool
}
func NewRouter(opts *RouterOpts) *mux.Router {
if !opts.DisableWebsocket {
m := InitMelody()
http.HandleFunc("/socat", func(w http.ResponseWriter, r *http.Request) {
m.HandleRequest(w, r)
})
}
/*
StrictSlash defines the trailing slash behavior for new routes. The initial value is false.
When true, if the route path is "/path/", accessing "/path" will perform a redirect to the former and vice versa. In other words, your application will always see the path as specified in the route.
When false, if the route path is "/path", accessing "/path/" will not match this route and vice versa.
The re-direct is a HTTP 301 (Moved Permanently). Note that when this is set for routes with a non-idempotent method (e.g. POST, PUT), the subsequent re-directed request will be made as a GET by most clients. Use middleware or client settings to modify this behaviour as needed.
Special case: when a route sets a path prefix using the PathPrefix() method, strict slash is ignored for that route because the redirect behavior can't be determined from a prefix alone. However, any subrouters created from that route inherit the original StrictSlash setting
*/
router := mux.NewRouter().StrictSlash(false)
router.Use(loggingMiddleware)
apiRoutes := router.NewRoute().Subrouter()
// All API routes use permissive CORS settings.
apiRoutes.Use(corsMiddleware)
// /ping is a simple server healthcheck endpoint
apiRoutes.Path("/ping").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("pong"))
})
apiJSONRoutes := apiRoutes.NewRoute().Subrouter()
jsonMiddleware := contentTypeMiddlewareFor("application/json")
apiJSONRoutes.Use(jsonMiddleware)
apiJSONRoutes.Path("/lastknown").HandlerFunc(getLastKnown).Methods(http.MethodGet)
apiJSONRoutes.Path("/catsnaps").HandlerFunc(handleGetCatSnaps).Methods(http.MethodGet)
authenticatedAPIRoutes := apiJSONRoutes.NewRoute().Subrouter()
authenticatedAPIRoutes.Use(tokenAuthenticationMiddleware)
populateRoutes := authenticatedAPIRoutes.NewRoute().Subrouter()
populateRoutes.Path("/populate/").HandlerFunc(populatePoints).Methods(http.MethodPost)
populateRoutes.Path("/populate").HandlerFunc(populatePoints).Methods(http.MethodPost)
return router
}