-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
185 lines (154 loc) · 3.57 KB
/
http.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
173
174
175
176
177
178
179
180
181
182
183
184
185
package stress
import (
"crypto/tls"
"encoding/json"
"net/http"
"regexp"
"runtime"
"time"
"github.com/op/go-logging"
)
var log = logging.MustGetLogger("stress")
type HandlerFunc func(http.ResponseWriter, *http.Request, Match)
type Route struct {
pattern string
handler HandlerFunc
pat *regexp.Regexp
}
func NewRoute(pattern string, handler HandlerFunc) *Route {
pat := regexp.MustCompile(pattern)
return &Route{
pattern: pattern,
handler: handler,
pat: pat,
}
}
func ServeJSON(w http.ResponseWriter, code int, jsonBytes []byte) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(jsonBytes)
}
func HttpError(w http.ResponseWriter, code int, msg ...string) {
var o struct {
Err string `json:"error,omitempty"`
}
if len(msg) != 0 {
o.Err = msg[0]
}
b, _ := json.Marshal(&o)
ServeJSON(w, code, b)
}
type HttpException struct {
Code int
Messages []string
}
func RaiseHttpError(code int, msg ...string) {
panic(HttpException{
Code: code,
Messages: msg,
})
}
type ServerHandler struct {
routes []*Route
}
func (handler *ServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
// we should process exceptions ourselves, because:
// - net/http just close TCP connection and log it via log.Printf() (not fine for aggregation system like Sentry)
// - to handle RaiseHttpError() calls (github.com/gin-gonic/gin can't do it)
// :TRICKY: we can catch anything but not panic(nil) ...
// do not use panic(nil), bro
if err := recover(); err != nil {
if httpError, ok := err.(HttpException); ok {
HttpError(w, httpError.Code, httpError.Messages...)
} else {
// copy-n-paste from http/net/server.go
// for more clear file logging
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
log.Errorf("http panic: %s\n%s", err, buf)
HttpError(w, http.StatusInternalServerError, "Something went wrong, bro")
}
}
}()
//fmt.Println(r.Method)
//fmt.Println(r.URL)
//fmt.Println(r.URL.Query())
//fmt.Println(r.Header)
//fmt.Println()
path := r.URL.Path
var route *Route
var m []int
for _, r := range handler.routes {
m = r.pat.FindStringSubmatchIndex(path)
if m != nil {
route = r
break
}
}
if route != nil {
route.handler(w, r, Match{
m,
path,
route,
})
} else {
http.NotFound(w, r)
}
}
func Match2Map(m []int, s string, pat *regexp.Regexp) map[string]string {
var result map[string]string
if m != nil {
result = make(map[string]string)
for i, name := range pat.SubexpNames() {
idx := m[2*i]
if idx >= 0 {
result[name] = s[idx:m[2*i+1]]
}
}
}
return result
}
type Match struct {
match []int
path string
route *Route
}
func (match Match) GetArgumentsMap() map[string]string {
return Match2Map(match.match, match.path, match.route.pat)
}
func (match Match) Arguments() []string {
var result []string
pairs := match.match
path := match.path
for i := range pairs {
if 2*i < len(pairs) && pairs[2*i] >= 0 {
res := path[pairs[2*i]:pairs[2*i+1]]
result = append(result, res)
} else {
break
}
}
return result
}
func ListenAndServe(addr string, routes []*Route, tlsConfig *tls.Config) {
server := &http.Server{
Addr: addr,
Handler: &ServerHandler{
routes,
},
TLSConfig: tlsConfig,
}
var err error
if tlsConfig != nil {
err = server.ListenAndServeTLS("", "")
} else {
err = server.ListenAndServe()
}
CheckError(err)
}
type Duration time.Duration
func (d Duration) MarshalText() (text []byte, err error) {
return []byte(time.Duration(d).String()), nil
}