fix: some api bug
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type HeaderExtractorMiddleware struct{}
|
||||
|
||||
func NewHeaderExtractorMiddleware() *HeaderExtractorMiddleware {
|
||||
return &HeaderExtractorMiddleware{}
|
||||
}
|
||||
|
||||
func (m *HeaderExtractorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header
|
||||
logx.Infof("headerExtractorMiddleware header: %v", header)
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
if userID := r.Header.Get("x-auth-user-id"); userID != "" {
|
||||
if parsed, err := strconv.ParseInt(userID, 10, 64); err == nil {
|
||||
ctx = context.WithValue(ctx, "user_id", parsed)
|
||||
} else {
|
||||
logx.Errorf("invalid x-auth-user-id header: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if isAdmin := r.Header.Get("x-auth-is-admin"); isAdmin != "" {
|
||||
if parsed, err := strconv.ParseBool(isAdmin); err == nil {
|
||||
ctx = context.WithValue(ctx, "is_admin", parsed)
|
||||
} else {
|
||||
logx.Errorf("invalid x-auth-is-admin header: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if requestID := r.Header.Get("x-request-id"); requestID != "" {
|
||||
ctx = context.WithValue(ctx, "request_id", requestID)
|
||||
ctx = context.WithValue(ctx, "rid", requestID)
|
||||
}
|
||||
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type RequestIdMiddleware struct{}
|
||||
|
||||
func NewRequestMiddleware() *RequestIdMiddleware {
|
||||
return &RequestIdMiddleware{}
|
||||
}
|
||||
|
||||
func (m *RequestIdMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
requestId := r.Header.Get("X-Request-Id")
|
||||
if requestId != "" {
|
||||
ctx = context.WithValue(ctx, "request_id", requestId)
|
||||
}
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user