new
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
BrandKey = "X-Brand"
|
||||
PlatformKey = "X-Platform"
|
||||
)
|
||||
|
||||
type SourceInterceptorMiddleware struct {
|
||||
}
|
||||
|
||||
func NewSourceInterceptorMiddleware() *SourceInterceptorMiddleware {
|
||||
return &SourceInterceptorMiddleware{}
|
||||
}
|
||||
|
||||
func (m *SourceInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// 获取请求头 X-Brand 和 X-Platform 的值
|
||||
brand := r.Header.Get(BrandKey)
|
||||
platform := r.Header.Get(PlatformKey)
|
||||
|
||||
// 将值放入新的 context 中
|
||||
ctx := r.Context()
|
||||
if brand != "" {
|
||||
ctx = context.WithValue(ctx, "brand", brand)
|
||||
}
|
||||
if platform != "" {
|
||||
ctx = context.WithValue(ctx, "platform", platform)
|
||||
}
|
||||
|
||||
// 通过 r.WithContext 将更新后的 ctx 传递给后续的处理函数
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
// 传递给下一个处理器
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user