@@ -15,6 +15,7 @@ import (
15
15
"regexp"
16
16
"runtime"
17
17
"strconv"
18
+ "strings"
18
19
"time"
19
20
)
20
21
@@ -262,6 +263,34 @@ func (s *Server) tryServingFile(name string, req *http.Request, w http.ResponseW
262
263
return false
263
264
}
264
265
266
+ func (s * Server ) logRequest (ctx Context , sTime time.Time ) {
267
+ //log the request
268
+ var logEntry bytes.Buffer
269
+ req := ctx .Request
270
+ requestPath := req .URL .Path
271
+
272
+ duration := time .Now ().Sub (sTime )
273
+ var client string
274
+
275
+ // We suppose RemoteAddr is of the form Ip:Port as specified in the Request
276
+ // documentation at http://golang.org/pkg/net/http/#Request
277
+ pos := strings .LastIndex (req .RemoteAddr , ":" )
278
+ if pos > 0 {
279
+ client = req .RemoteAddr [0 :pos ]
280
+ } else {
281
+ client = req .RemoteAddr
282
+ }
283
+
284
+ fmt .Fprintf (& logEntry , "%s - \033 [32;1m %s %s\033 [0m - %v" , client , req .Method , requestPath , duration )
285
+
286
+ if len (ctx .Params ) > 0 {
287
+ fmt .Fprintf (& logEntry , " - \033 [37;1mParams: %v\033 [0m\n " , ctx .Params )
288
+ }
289
+
290
+ ctx .Server .Logger .Print (logEntry .String ())
291
+
292
+ }
293
+
265
294
// the main route handler in web.go
266
295
// Tries to handle the given request.
267
296
// Finds the route matching the request, and execute the callback associated
@@ -272,23 +301,20 @@ func (s *Server) routeHandler(req *http.Request, w http.ResponseWriter) (unused
272
301
requestPath := req .URL .Path
273
302
ctx := Context {req , map [string ]string {}, s , w }
274
303
275
- //log the request
276
- var logEntry bytes. Buffer
277
- fmt . Fprintf ( & logEntry , " \033 [32;1m%s %s \033 [0m" , req . Method , requestPath )
304
+ //set some default headers
305
+ ctx . SetHeader ( "Server" , "web.go" , true )
306
+ tm := time . Now (). UTC ( )
278
307
279
308
//ignore errors from ParseForm because it's usually harmless.
280
309
req .ParseForm ()
281
310
if len (req .Form ) > 0 {
282
311
for k , v := range req .Form {
283
312
ctx .Params [k ] = v [0 ]
284
313
}
285
- fmt .Fprintf (& logEntry , "\n \033 [37;1mParams: %v\033 [0m\n " , ctx .Params )
286
314
}
287
- ctx .Server .Logger .Print (logEntry .String ())
288
315
289
- //set some default headers
290
- ctx .SetHeader ("Server" , "web.go" , true )
291
- tm := time .Now ().UTC ()
316
+ defer s .logRequest (ctx , tm )
317
+
292
318
ctx .SetHeader ("Date" , webTime (tm ), true )
293
319
294
320
if req .Method == "GET" || req .Method == "HEAD" {
0 commit comments