104 lines
1.8 KiB
Go
104 lines
1.8 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/url"
|
|
"sync"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gin-gonic/gin/binding"
|
|
)
|
|
|
|
var (
|
|
ctxPool sync.Pool
|
|
)
|
|
|
|
type Context struct {
|
|
ctx *gin.Context
|
|
}
|
|
|
|
func (c *Context) Context() context.Context {
|
|
return c.ctx.Request.Context()
|
|
}
|
|
|
|
func (c *Context) Gin() *gin.Context {
|
|
return c.ctx
|
|
}
|
|
|
|
func (c *Context) Request() *http.Request {
|
|
return c.ctx.Request
|
|
}
|
|
|
|
func (c *Context) Response() http.ResponseWriter {
|
|
return c.ctx.Writer
|
|
}
|
|
|
|
func (c *Context) ClientIP() string {
|
|
return c.ctx.ClientIP()
|
|
}
|
|
|
|
func (c *Context) Param(key string) string {
|
|
return c.ctx.Param(key)
|
|
}
|
|
|
|
func (c *Context) Query(key string) string {
|
|
qs := c.ctx.Request.URL.Query()
|
|
if qs != nil {
|
|
return qs.Get(key)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (c *Context) Bind(val any) (err error) {
|
|
// if params exists, try bind params first
|
|
if len(c.ctx.Params) > 0 {
|
|
qs := url.Values{}
|
|
for _, p := range c.ctx.Params {
|
|
qs.Set(p.Key, p.Value)
|
|
}
|
|
if err = binding.MapFormWithTag(val, qs, "json"); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if c.Request().Method == http.MethodGet {
|
|
values := c.Request().URL.Query()
|
|
return binding.MapFormWithTag(val, values, "json")
|
|
}
|
|
return c.ctx.Bind(val)
|
|
}
|
|
|
|
func (c *Context) Error(code int, reason string) (err error) {
|
|
r := newResponse(code, reason, nil)
|
|
c.ctx.JSON(http.StatusOK, r)
|
|
return
|
|
}
|
|
|
|
func (c *Context) Success(value any) (err error) {
|
|
r := newResponse(http.StatusOK, "", value)
|
|
c.ctx.JSON(http.StatusOK, r)
|
|
return
|
|
}
|
|
|
|
func (c *Context) reset(ctx *gin.Context) {
|
|
c.ctx = ctx
|
|
}
|
|
|
|
func newContext(ctx *gin.Context) *Context {
|
|
v := ctxPool.Get()
|
|
if v == nil {
|
|
return &Context{
|
|
ctx: ctx,
|
|
}
|
|
}
|
|
if c, ok := v.(*Context); ok {
|
|
c.reset(ctx)
|
|
return c
|
|
}
|
|
return &Context{ctx: ctx}
|
|
}
|
|
|
|
func putContext(c *Context) {
|
|
ctxPool.Put(c)
|
|
}
|