46 lines
1 KiB
Go
46 lines
1 KiB
Go
package core
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func LogMiddleware(next func(w *Response, r *http.Request)) func(w *Response, r *http.Request) {
|
|
return func(w *Response, r *http.Request) {
|
|
now := time.Now()
|
|
next(w, r)
|
|
elapsed := time.Since(now)
|
|
|
|
// Use NCSA common log format
|
|
ip := r.RemoteAddr
|
|
timestamp := time.Now().Format("02/Jan/2006:15:04:05 -0700")
|
|
method := r.Method
|
|
url := r.URL.Path
|
|
protocol := r.Proto
|
|
status := w.Status
|
|
size := w.Size
|
|
|
|
slog.Info(fmt.Sprintf("%s - - [%s] \"%s %s %s\" %d %d %s", ip, timestamp, method, url, protocol, status, size, elapsed))
|
|
}
|
|
}
|
|
|
|
func ErrorMiddleware(next func(w *Response, r *http.Request)) func(w *Response, r *http.Request) {
|
|
return func(w *Response, r *http.Request) {
|
|
defer func() {
|
|
if err := recover(); err != nil {
|
|
if err, ok := err.(error); ok {
|
|
json, _ := json.Marshal(NewInternalServerError(err))
|
|
w.Json(json)
|
|
} else {
|
|
json, _ := json.Marshal(NewInternalServerError(nil))
|
|
w.Json(json)
|
|
}
|
|
}
|
|
}()
|
|
|
|
next(w, r)
|
|
}
|
|
}
|