mirror of
https://github.com/Luzifer/mondash.git
synced 2024-11-10 00:20:02 +00:00
Write access-log
This commit is contained in:
parent
b9e5281a87
commit
a3a148b0ff
2 changed files with 54 additions and 1 deletions
40
logResponseWriter.go
Normal file
40
logResponseWriter.go
Normal file
|
@ -0,0 +1,40 @@
|
|||
package main
|
||||
|
||||
import "net/http"
|
||||
|
||||
// LogResponseWriter wraps the standard http.ResponseWritter allowing for more
|
||||
// verbose logging
|
||||
type LogResponseWriter struct {
|
||||
Status int
|
||||
Size int
|
||||
http.ResponseWriter
|
||||
}
|
||||
|
||||
// NewLogResponseWriter instanciates a new LogResponseWriter
|
||||
func NewLogResponseWriter(res http.ResponseWriter) *LogResponseWriter {
|
||||
// Default the status code to 200
|
||||
return &LogResponseWriter{200, 0, res}
|
||||
}
|
||||
|
||||
// Header returns & satisfies the http.ResponseWriter interface
|
||||
func (w *LogResponseWriter) Header() http.Header {
|
||||
return w.ResponseWriter.Header()
|
||||
}
|
||||
|
||||
// Write satisfies the http.ResponseWriter interface and
|
||||
// captures data written, in bytes
|
||||
func (w *LogResponseWriter) Write(data []byte) (int, error) {
|
||||
|
||||
written, err := w.ResponseWriter.Write(data)
|
||||
w.Size += written
|
||||
|
||||
return written, err
|
||||
}
|
||||
|
||||
// WriteHeader satisfies the http.ResponseWriter interface and
|
||||
// allows us to cach the status code
|
||||
func (w *LogResponseWriter) WriteHeader(statusCode int) {
|
||||
|
||||
w.Status = statusCode
|
||||
w.ResponseWriter.WriteHeader(statusCode)
|
||||
}
|
15
main.go
15
main.go
|
@ -4,6 +4,7 @@ import (
|
|||
"crypto/md5"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
|
@ -49,10 +50,22 @@ func main() {
|
|||
|
||||
go runWelcomePage(cfg)
|
||||
|
||||
http.Handle("/", r)
|
||||
http.Handle("/", logHTTPRequest(r))
|
||||
http.ListenAndServe(cfg.Listen, nil)
|
||||
}
|
||||
|
||||
func logHTTPRequest(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(res http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now().UnixNano()
|
||||
w := NewLogResponseWriter(res)
|
||||
|
||||
h.ServeHTTP(w, r)
|
||||
|
||||
d := (time.Now().UnixNano() - start) / 1000
|
||||
log.Printf("%s %s %d %dµs %dB\n", r.Method, r.URL.Path, w.Status, d, w.Size)
|
||||
})
|
||||
}
|
||||
|
||||
func generateAPIKey() string {
|
||||
t := time.Now().String()
|
||||
sum := md5.Sum([]byte(t))
|
||||
|
|
Loading…
Reference in a new issue