feat: update template
This commit is contained in:
53
internal/middleware/request_context.go
Normal file
53
internal/middleware/request_context.go
Normal file
@@ -0,0 +1,53 @@
|
||||
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))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user