dorisbot/pkg/context/context.go

79 lines
1.6 KiB
Go
Raw Normal View History

2019-09-16 09:16:58 +00:00
package context
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// Context -
type Context struct {
*gin.Context
}
// CustomMiddle -
type CustomMiddle func(*Context)
// PatchCtx -
func PatchCtx(handler CustomMiddle) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := &Context{Context: c}
handler(ctx)
}
}
// BindData - bind form body to interface{}
func (c *Context) BindData(i interface{}) error {
b := binding.Default(c.Request.Method, c.ContentType())
return c.ShouldBindWith(i, b)
}
// CustomRes -
func (c *Context) CustomRes(status int, msg ...interface{}) {
var resp interface{}
if len(msg) == 0 {
resp = make(map[string]string)
} else {
resp = msg[0]
}
c.AbortWithStatusJSON(status, resp)
}
// Success -
func (c *Context) Success(msg ...interface{}) {
var resp interface{}
if len(msg) == 0 {
resp = make(map[string]string)
resp.(map[string]string)["message"] = "Success"
} else {
resp = msg[0]
}
c.AbortWithStatusJSON(http.StatusOK, msg)
}
// DataFormat -
func (c *Context) DataFormat(msg ...interface{}) {
var resp interface{}
if len(msg) == 0 {
resp = make(map[string]string)
resp.(map[string]string)["message"] = "data format error"
} else {
resp = msg[0]
}
c.AbortWithStatusJSON(http.StatusBadRequest, resp)
}
// ServerError -
func (c *Context) ServerError(msg ...interface{}) {
var resp interface{}
if len(msg) == 0 {
resp = make(map[string]string)
resp.(map[string]string)["message"] = "internal error"
} else {
resp = msg[0]
}
c.AbortWithStatusJSON(http.StatusInternalServerError, msg)
}