api-base/pkg/context/context.go

76 lines
1.5 KiB
Go

package context
import (
"context"
"go-api/pkg/response"
"github.com/gin-gonic/gin"
)
type C struct {
*gin.Context
}
type CustomHandler func(c *C)
func PatchContext(handler CustomHandler) gin.HandlerFunc {
return func(ctx *gin.Context) {
c := &C{
Context: ctx,
}
handler(c)
}
}
func (c *C) getContext() context.Context {
return c.Request.Context()
}
// Success
// send success body to client
func (c *C) Success(i ...interface{}) {
r := response.Get(response.RespSuccess)
var resp interface{} = r.Body
if len(i) > 0 {
resp = i[0]
}
c.AbortWithStatusJSON(r.Status, resp)
}
func (c *C) DataFormat(code ...response.MessageCode) {
r := response.Get(response.RespDataFormat, code...)
c.AbortWithStatusJSON(r.Status, r.Body)
}
func (c *C) NotFound(code ...response.MessageCode) {
r := response.Get(response.RespNotFound, code...)
c.AbortWithStatusJSON(r.Status, r.Body)
}
func (c *C) Forbidden(code ...response.MessageCode) {
r := response.Get(response.RespNotFound, code...)
c.AbortWithStatusJSON(r.Status, r.Body)
}
func (c *C) ServerError(code ...response.MessageCode) {
r := response.Get(response.RespInternalError, code...)
c.AbortWithStatusJSON(r.Status, r.Body)
}
func (c *C) CustomResp(rt response.RespType, code response.MessageCode, data ...interface{}) {
r := response.Get(rt)
if code != r.Body.MessageCode {
r.Body.MessageCode, r.Body.Message = response.GetCodeMessage(code)
}
var resp interface{} = r.Body
if len(data) > 0 {
resp = data[0]
}
c.AbortWithStatusJSON(r.Status, resp)
}