Skip to content

Commit

Permalink
gin context
Browse files Browse the repository at this point in the history
兼容gin grpc 的 context
  • Loading branch information
xxjwxc committed Jun 3, 2020
1 parent ab15f7d commit 2905984
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
24 changes: 24 additions & 0 deletions api/context.go
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)
}
49 changes: 49 additions & 0 deletions api/gin.go
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)
}

0 comments on commit 2905984

Please sign in to comment.