re-write with std usage of net/http
This commit is contained in:
parent
c107d94b11
commit
81bc046237
10 changed files with 419 additions and 97 deletions
56
middleware/logging.go
Normal file
56
middleware/logging.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.okseby.com/okseby/playground-go/logger"
|
||||
)
|
||||
|
||||
// ANSI color codes
|
||||
const (
|
||||
ColorReset = "\033[0m"
|
||||
ColorRed = "\033[31m"
|
||||
ColorGreen = "\033[32m"
|
||||
ColorYellow = "\033[33m"
|
||||
ColorCyan = "\033[36m"
|
||||
ColorGrey = "\033[90m"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(code int) {
|
||||
r.status = code
|
||||
r.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Logger(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
recorder := &statusRecorder{ResponseWriter: w, status: 200}
|
||||
next.ServeHTTP(recorder, r)
|
||||
|
||||
duration := time.Since(start)
|
||||
|
||||
statusColor := ColorGreen
|
||||
switch {
|
||||
case recorder.status >= 500:
|
||||
statusColor = ColorRed
|
||||
case recorder.status >= 400:
|
||||
statusColor = ColorRed
|
||||
case recorder.status >= 300:
|
||||
statusColor = ColorYellow
|
||||
}
|
||||
|
||||
logger.Info("%s%-7s%s %s%-30s%s %s%d%s [%s]",
|
||||
ColorCyan, r.Method, ColorReset,
|
||||
ColorGrey, r.URL.Path, ColorReset,
|
||||
statusColor, recorder.status, ColorReset,
|
||||
duration.Round(time.Millisecond),
|
||||
)
|
||||
})
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue