-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
兼容gin grpc 的 context
- Loading branch information
Showing
2 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/* | ||
context 跟gin.context 的转换 | ||
*/ | ||
package api | ||
|
||
import ( | ||
"context" | ||
) | ||
|
||
// Context Wrapping gin context to custom context | ||
type Context struct { // 包装gin的上下文到自定义context | ||
context.Context | ||
} | ||
|
||
// SetValue 设置key v | ||
func (c *Context) SetValue(key interface{}, value interface{}) { | ||
ctx := context.WithValue(c.Context, key, value) | ||
c.Context = ctx | ||
} | ||
|
||
// GetValue 获取key | ||
func (c *Context) GetValue(key interface{}) interface{} { | ||
return c.Context.Value(key) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package api | ||
|
||
import ( | ||
"context" | ||
"net/http/httptest" | ||
|
||
"github.com/xxjwxc/public/mylog" | ||
|
||
"github.com/gin-gonic/gin" | ||
) | ||
|
||
// gin key | ||
type ginHTTPReq struct{} | ||
|
||
// GetVersion Get the version by req url | ||
func (c *Context) GetVersion() string { // 获取版本号 | ||
return c.GetGinCtx().Param("version") | ||
} | ||
|
||
//WriteJSON 写入json对象 | ||
func (c *Context) WriteJSON(obj interface{}) { | ||
c.GetGinCtx().JSON(200, obj) | ||
} | ||
|
||
// GetGinCtx 获取 gin.Context | ||
func (c *Context) GetGinCtx() *gin.Context { | ||
req := c.GetValue(ginHTTPReq{}) | ||
if req == nil { | ||
mylog.ErrorString("using default gin.context") | ||
r, _ := gin.CreateTestContext(httptest.NewRecorder()) | ||
return r | ||
} | ||
if r, ok := req.(*gin.Context); ok { | ||
return r | ||
} | ||
return nil | ||
} | ||
|
||
// NewCtx Create a new custom context | ||
func NewCtx(c *gin.Context) *Context { // 新建一个自定义context | ||
ctx := &Context{context.TODO()} | ||
ctx.SetValue(ginHTTPReq{}, c) | ||
return ctx | ||
} | ||
|
||
// NewAPIFunc default of custom handlefunc | ||
func NewAPIFunc(c *gin.Context) interface{} { | ||
return NewCtx(c) | ||
} |