54 lines
1010 B
Go
54 lines
1010 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"server/internal/pkg/httputil"
|
|
"time"
|
|
|
|
gonanoid "github.com/matoous/go-nanoid/v2"
|
|
)
|
|
|
|
func generateRequestID() string {
|
|
id, _ := gonanoid.New(16) // 16字符
|
|
return id
|
|
}
|
|
|
|
type RequestContextMiddleware struct {
|
|
}
|
|
|
|
func NewRequestContextMiddleware() *RequestContextMiddleware {
|
|
return &RequestContextMiddleware{}
|
|
}
|
|
|
|
func (m *RequestContextMiddleware) Middleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
reqCtx := &RequestContext{
|
|
RequestID: generateRequestID(),
|
|
StartTime: time.Now(),
|
|
Method: r.Method,
|
|
Path: r.URL.RequestURI(),
|
|
ClientIp: httputil.ClientIP(r),
|
|
UserAgent: r.UserAgent(),
|
|
Referer: r.Referer(),
|
|
}
|
|
|
|
userCtx := &UserContext{
|
|
UserID: 0,
|
|
IsAdmin: false,
|
|
TokenVersion: 0,
|
|
}
|
|
|
|
ctx := WithRequestContext(
|
|
r.Context(),
|
|
reqCtx,
|
|
)
|
|
|
|
ctx = WithUserContext(
|
|
ctx,
|
|
userCtx,
|
|
)
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|