package global import ( "fmt" "net/http" "strconv" "time" "arimelody-web/colour" ) func DefaultHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Server", "arimelody.me") w.Header().Add("Cache-Control", "max-age=2592000") next.ServeHTTP(w, r) }) } type LoggingResponseWriter struct { http.ResponseWriter Code int } func (lrw *LoggingResponseWriter) WriteHeader(code int) { lrw.Code = code lrw.ResponseWriter.WriteHeader(code) } func HTTPLog(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() lrw := LoggingResponseWriter{w, http.StatusOK} next.ServeHTTP(&lrw, r) after := time.Now() difference := (after.Nanosecond() - start.Nanosecond()) / 1_000_000 elapsed := "<1" if difference >= 1 { elapsed = strconv.Itoa(difference) } codeColour := colour.Reset if lrw.Code - 600 <= 0 { codeColour = colour.Red } if lrw.Code - 500 <= 0 { codeColour = colour.Yellow } if lrw.Code - 400 <= 0 { codeColour = colour.White } if lrw.Code - 300 <= 0 { codeColour = colour.Green } fmt.Printf("[%s] %s %s - %s%d%s (%sms) (%s)\n", after.Format(time.UnixDate), r.Method, r.URL.Path, codeColour, lrw.Code, colour.Reset, elapsed, r.Header["User-Agent"][0]) }) }