diff --git a/util/fake.go b/util/fake.go new file mode 100644 index 0000000..d7b5ae0 --- /dev/null +++ b/util/fake.go @@ -0,0 +1,71 @@ +// Package util ... +// +// Description : util ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2025-08-18 21:36 +package util + +import ( + "net/http" + "net/url" + "os" + "reflect" + "sync" + + "git.zhangdeman.cn/zhangdeman/consts" + "github.com/gin-gonic/gin" +) + +const ( + FakeUriDefault = "git.zhangdeman.cn/zhangdeman/gin@util/fake" +) + +// FakeGinContext 伪造gin.Context +func FakeGinContext(fakeUri string, ctxData map[string]any) *gin.Context { + if fakeUri == "" { + fakeUri = FakeUriDefault + } + h, _ := os.Hostname() + ctx := &gin.Context{ + Request: &http.Request{ + Method: http.MethodPost, + URL: &url.URL{ + Scheme: consts.SchemeHTTPS.String(), + User: nil, + Host: h, + Path: fakeUri, + }, + Header: map[string][]string{}, + Host: h, + RemoteAddr: "localhost", + RequestURI: fakeUri, + }, + Keys: map[string]any{}, + } + ctxReflectVal := reflect.ValueOf(ctx).Elem() + field := ctxReflectVal.FieldByName("mu") + if field.IsValid() && field.CanSet() { + field.Set(reflect.ValueOf(sync.Mutex{})) + } + for k, v := range ctxData { + ctx.Set(k, v) + } + ctx.Copy() + return ctx +} + +// Copy 复制gin.Context, 解决原生复制没有初始化mu的问题 +func Copy(ctx *gin.Context) *gin.Context { + if nil == ctx { + return nil + } + newCtx := ctx.Copy() + ctxReflectVal := reflect.ValueOf(newCtx).Elem() + field := ctxReflectVal.FieldByName("mu") + if field.IsValid() && field.CanSet() { + field.Set(reflect.ValueOf(sync.Mutex{})) + } + return newCtx +}