forked from poiriermike/battlesnake-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.go
More file actions
53 lines (42 loc) · 1.08 KB
/
helpers.go
File metadata and controls
53 lines (42 loc) · 1.08 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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
)
func respond(res http.ResponseWriter, obj interface{}) {
res.Header().Set("Content-Type", "application/json")
json.NewEncoder(res).Encode(obj)
res.Write([]byte("\n"))
}
func dump(obj interface{}) {
data, err := json.MarshalIndent(obj, "", " ")
if err == nil {
log.Printf(string(data))
}
}
const LogFormat = `"%s %s %s %d %d" %f`
func LoggingHandler(next http.Handler) http.Handler {
var logger = log.New(os.Stderr, "", log.LstdFlags)
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
loggingWriter := &LoggingResponseWriter{res, http.StatusOK}
startTime := time.Now()
next.ServeHTTP(loggingWriter, req)
elapsedTime := time.Now().Sub(startTime)
logger.Printf(
LogFormat,
req.Method, req.RequestURI, req.Proto,
loggingWriter.statusCode, 0, elapsedTime.Seconds(),
)
})
}
type LoggingResponseWriter struct {
http.ResponseWriter
statusCode int
}
func (res *LoggingResponseWriter) WriteHeader(code int) {
res.statusCode = code
res.ResponseWriter.WriteHeader(code)
}