feat: 新增访客拦截器

This commit is contained in:
2026-03-03 00:58:22 +08:00
parent 52cfe1b911
commit 00a0a01b17
7 changed files with 566 additions and 0 deletions

View File

@@ -12,6 +12,8 @@ type UserInfo struct {
Trace string `json:"trace"`
VisitTime time.Time `json:"visit_time"`
FromIP string `json:"from_ip"`
Province string `json:"province"`
City string `json:"city"`
}
// contextKey is the type for context keys to prevent collisions
@@ -24,6 +26,8 @@ const (
TraceKey contextKey = "trace"
VisitTimeKey contextKey = "visitTime"
FromIPKey contextKey = "fromIP"
ProvinceKey contextKey = "province"
CityKey contextKey = "city"
)
// GetUserID returns user ID from context
@@ -121,6 +125,44 @@ func SetFromIP(ctx context.Context, fromIP string) context.Context {
return context.WithValue(ctx, FromIPKey, fromIP)
}
// GetProvince returns province from context
func GetProvince(ctx context.Context) string {
if ctx == nil {
return ""
}
if val, ok := ctx.Value(ProvinceKey).(string); ok {
return val
}
return ""
}
// SetProvince sets province in context and returns new context
func SetProvince(ctx context.Context, province string) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, ProvinceKey, province)
}
// GetCity returns city from context
func GetCity(ctx context.Context) string {
if ctx == nil {
return ""
}
if val, ok := ctx.Value(CityKey).(string); ok {
return val
}
return ""
}
// SetCity sets city in context and returns new context
func SetCity(ctx context.Context, city string) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, CityKey, city)
}
// FromContext builds UserInfo from individual context fields
// Returns nil if no fields are found
func FromContext(ctx context.Context) *UserInfo {
@@ -150,6 +192,14 @@ func FromContext(ctx context.Context) *UserInfo {
info.FromIP = fromIP
hasData = true
}
if province := GetProvince(ctx); province != "" {
info.Province = province
hasData = true
}
if city := GetCity(ctx); city != "" {
info.City = city
hasData = true
}
if !hasData {
return nil
@@ -171,6 +221,8 @@ func ToContext(ctx context.Context, userInfo *UserInfo) context.Context {
ctx = SetTrace(ctx, userInfo.Trace)
ctx = SetVisitTime(ctx, userInfo.VisitTime)
ctx = SetFromIP(ctx, userInfo.FromIP)
ctx = SetProvince(ctx, userInfo.Province)
ctx = SetCity(ctx, userInfo.City)
return ctx
}
@@ -211,3 +263,15 @@ func (u *UserInfo) WithVisitTime(visitTime time.Time) *UserInfo {
u.VisitTime = visitTime
return u
}
// WithProvince sets the province
func (u *UserInfo) WithProvince(province string) *UserInfo {
u.Province = province
return u
}
// WithCity sets the city
func (u *UserInfo) WithCity(city string) *UserInfo {
u.City = city
return u
}