增加ctx copy的包装方法

This commit is contained in:
2025-02-28 11:44:56 +08:00
parent 3432087fbd
commit ac5776f3f6
3 changed files with 47 additions and 7 deletions

View File

@ -115,8 +115,8 @@ func (wh *wrapperHandle) GetContentType(ctx *gin.Context, defaultVal string) str
if nil == ctx {
return defaultVal
}
contentType := strings.ToLower(ctx.ContentType())
return wrapper.TernaryOperator.String(len(contentType) > 0, wrapper.String(contentType), wrapper.String(defaultVal)).Value()
contentTypeVal := strings.ToLower(ctx.ContentType())
return wrapper.TernaryOperator.String(len(contentTypeVal) > 0, wrapper.String(contentTypeVal), wrapper.String(defaultVal)).Value()
}
// GetDomain 获取请求Domain
@ -268,3 +268,37 @@ func (wh *wrapperHandle) ParseCookie(ctx *gin.Context) map[string]string {
}
return cookieData
}
// Copy 复制context
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:00 2025/2/28
//
// - ctx *gin.Context 基于哪一个context复制context
// - isCopyContextValue bool : 是否继承父级ctx的自定义value
func (wh *wrapperHandle) Copy(ctx *gin.Context, isCopyContextValue bool, excludeKeyList []string) *gin.Context {
if nil == ctx {
return nil
}
newContext := ctx.Copy()
excludeKeyTable := map[string]bool{}
for _, excludeKey := range excludeKeyList {
excludeKeyTable[excludeKey] = true
}
if isCopyContextValue {
// 上下文设置的业务数据值也继承下来, TODO: 并发读写此处可能panic
for k, v := range newContext.Keys {
if !excludeKeyTable[k] {
// 没有指定不继承
ctx.Set(k, v)
}
}
}
// 设置父级context
ctx.Set("parent_context", ctx)
if nil == ctx.Value("root_context") {
ctx.Set("root_context", ctx)
}
return newContext
}