-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttputil.go
252 lines (221 loc) · 5.52 KB
/
httputil.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
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
// Package httputil provides HTTP utility functions as well as its own
// http.Handler to complement the "net/http" and "net/http/httputil"
// packages found in the standard library.
package httputil
import (
"fmt"
"html"
"log"
"net"
"net/http"
"runtime/debug"
"strconv"
"strings"
"time"
)
// Common Log Format
// See <http://httpd.apache.org/docs/1.3/logs.html#common>
const CommonLogFmt = `%s - - [%s] "%s %s %s" %d %d "%s" "%s" %d`
var (
LogFmt = CommonLogFmt // Log format to use
notify = []chan *Access{}
)
// Notify sends all HTTP access events to the specified channel.
func Notify(ch chan *Access) {
notify = append(notify, ch)
}
// Access represents a single HTTP access event (an answered request).
type Access struct {
RemoteAddr string
Time time.Time
Method string
RequestURI string
Proto string
StatusCode int
ContentLength int64
Referer string
UserAgent string
Duration time.Duration
Request *http.Request
}
// String returns the string representation of an *Access according
// to LogFmt.
func (a *Access) String() string {
return fmt.Sprintf(LogFmt,
a.RemoteAddr,
a.Time.Format("02/Jan/2006:15:04:05 -0700"),
a.Method,
a.RequestURI,
a.Proto,
a.StatusCode,
a.ContentLength,
a.Referer,
a.UserAgent,
a.Duration/time.Millisecond)
}
// Handler implements http.Handler.
type Handler struct {
inner http.Handler
contentType string
accept string
allow []string
}
// NewHandler returns a new Handler which wraps the given http.Handler.
func NewHandler(inner http.Handler, ctype string) *Handler {
return &Handler{
inner: inner,
contentType: ctype,
}
}
// Accept instructs the handler to only fulfill requests
// which have an Accept header of the given MIME type.
// Otherwise, a 406 Not Acceptable is returned.
func (h *Handler) Accept(mime string) {
h.accept = mime
}
// Allow instructs the handler to only fulfill requests
// which use one of the given HTTP methods.
// Otherwise, a 405 Method Not Allowed is returned.
func (h *Handler) Allow(methods ...string) {
h.allow = methods
}
// ResponseWriter wraps an http.ResponseWriter with
// additional capabilities.
type ResponseWriter struct {
StatusCode int
ContentType string
inner http.ResponseWriter
}
// HasStatus returns whether or not the ResponseWriter has
// a status.
func (rw *ResponseWriter) HasStatus() bool {
return rw.StatusCode != 0
}
// WriteHeader wraps (*http.ResponseWriter).WriteHeader and
// records the given status.
func (rw *ResponseWriter) WriteHeader(status int) {
rw.StatusCode = status
rw.inner.WriteHeader(status)
}
// Write wraps (*http.ResponseWriter).Write.
func (rw *ResponseWriter) Write(b []byte) (int, error) {
return rw.inner.Write(b)
}
// Write wraps (*http.ResponseWriter).Header.
func (rw *ResponseWriter) Header() http.Header {
return rw.inner.Header()
}
// Error wraps http.Error by writing appropriate error messages
// depending on the handler's Content-Type.
//
// For example, with the Content-Type set to application/json
// and the error string "oops!", the response body would be
// `{"error":"oops!"}`
func Error(w http.ResponseWriter, err string, code int) {
if rw, ok := w.(*ResponseWriter); ok {
switch rw.ContentType {
case "application/json":
err = fmt.Sprintf(`{"error":%s,"status":%d}`, strconv.QuoteToASCII(err), code)
case "text/html":
err = html.EscapeString(err)
case "text/plain":
fallthrough
default:
err = "error: " + err
}
}
http.Error(w, err, code)
}
func logRequest(r *http.Request, statusCode int, delta time.Duration) {
var referer, remoteAddr, userAgent string
if h, ok := r.Header["Referer"]; ok {
referer = h[0]
} else {
referer = "-"
}
if h, ok := r.Header["X-Forwarded-For"]; ok {
remoteAddr = h[0]
} else {
if host, _, err := net.SplitHostPort(r.RemoteAddr); err != nil {
remoteAddr = "?"
} else {
remoteAddr = host
}
}
if h, ok := r.Header["User-Agent"]; ok {
userAgent = h[0]
} else {
userAgent = "-"
}
for _, ch := range notify {
ch <- &Access{
remoteAddr,
time.Now(),
r.Method,
r.RequestURI,
r.Proto,
statusCode,
r.ContentLength,
referer,
userAgent,
delta,
r,
}
}
}
// ServeHTTP serves an HTTP request by calling the underlying http.Handler.
// Request duration and status are logged.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var delta time.Duration
rw := &ResponseWriter{inner: w, ContentType: h.contentType}
rw.Header().Set("Content-Type", h.contentType)
defer func() {
if e := recover(); e != nil {
if !rw.HasStatus() {
rw.WriteHeader(http.StatusInternalServerError)
}
log.Printf("panic: %v", e)
debug.PrintStack()
}
if rw.HasStatus() {
logRequest(r, rw.StatusCode, delta)
} else {
logRequest(r, http.StatusOK, delta)
}
}()
t := time.Now()
h.serveRequest(rw, r)
delta = time.Since(t)
}
func (h *Handler) serveRequest(w http.ResponseWriter, r *http.Request) {
mime := r.Header.Get("Accept")
if mime != "" && mime != "*/*" && h.accept != "" && mime != h.accept {
w.Header().Set("Accept", h.accept)
w.WriteHeader(http.StatusNotAcceptable)
return
}
if h.allow != nil {
allowed := false
for _, m := range h.allow {
if r.Method == m {
allowed = true
break
}
}
if !allowed {
w.Header().Set("Allow", strings.Join(h.allow, ", "))
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
}
h.inner.ServeHTTP(w, r)
}
func init() {
ch := make(chan *Access, 1)
Notify(ch)
go func() {
for {
log.Println((<-ch).String())
}
}()
}