2024-07-31 03:09:22 +00:00
|
|
|
package global
|
|
|
|
|
|
|
|
import (
|
2024-08-01 23:53:19 +00:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
2024-07-31 03:09:22 +00:00
|
|
|
|
2024-09-03 07:07:45 +00:00
|
|
|
"arimelody-web/colour"
|
2024-08-01 23:53:19 +00:00
|
|
|
)
|
2024-07-31 18:17:58 +00:00
|
|
|
|
2024-08-01 00:39:18 +00:00
|
|
|
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")
|
2024-08-02 21:48:26 +00:00
|
|
|
next.ServeHTTP(w, r)
|
2024-08-01 00:39:18 +00:00
|
|
|
})
|
2024-07-31 03:09:22 +00:00
|
|
|
}
|
|
|
|
|
2024-07-31 18:17:58 +00:00
|
|
|
type LoggingResponseWriter struct {
|
2024-07-31 12:45:34 +00:00
|
|
|
http.ResponseWriter
|
2024-07-31 18:17:58 +00:00
|
|
|
Code int
|
2024-07-31 12:45:34 +00:00
|
|
|
}
|
|
|
|
|
2024-07-31 18:17:58 +00:00
|
|
|
func (lrw *LoggingResponseWriter) WriteHeader(code int) {
|
|
|
|
lrw.Code = code
|
|
|
|
lrw.ResponseWriter.WriteHeader(code)
|
2024-07-31 12:45:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func HTTPLog(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
start := time.Now()
|
|
|
|
|
2024-07-31 18:17:58 +00:00
|
|
|
lrw := LoggingResponseWriter{w, http.StatusOK}
|
2024-07-31 12:45:34 +00:00
|
|
|
|
2024-07-31 18:17:58 +00:00
|
|
|
next.ServeHTTP(&lrw, r)
|
2024-07-31 12:45:34 +00:00
|
|
|
|
|
|
|
after := time.Now()
|
|
|
|
difference := (after.Nanosecond() - start.Nanosecond()) / 1_000_000
|
|
|
|
elapsed := "<1"
|
|
|
|
if difference >= 1 {
|
|
|
|
elapsed = strconv.Itoa(difference)
|
|
|
|
}
|
|
|
|
|
2024-08-01 23:53:19 +00:00
|
|
|
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",
|
2024-07-31 12:45:34 +00:00
|
|
|
after.Format(time.UnixDate),
|
|
|
|
r.Method,
|
|
|
|
r.URL.Path,
|
2024-08-01 23:53:19 +00:00
|
|
|
codeColour,
|
2024-07-31 18:17:58 +00:00
|
|
|
lrw.Code,
|
2024-08-01 23:53:19 +00:00
|
|
|
colour.Reset,
|
2024-07-31 12:45:34 +00:00
|
|
|
elapsed,
|
|
|
|
r.Header["User-Agent"][0])
|
|
|
|
})
|
|
|
|
}
|
2024-08-01 00:39:18 +00:00
|
|
|
|