go-gallery/modules/context/context.go

64 lines
1.4 KiB
Go
Raw Normal View History

2018-04-17 09:16:03 +00:00
package context
import (
"git.trj.tw/golang/go-gallery/modules/apimsg"
"github.com/gin-gonic/gin"
2018-04-18 06:16:29 +00:00
"github.com/gin-gonic/gin/binding"
2018-04-17 09:16:03 +00:00
)
// Context custom patch context
type Context struct {
*gin.Context
2018-04-17 10:04:36 +00:00
C map[string]interface{}
2018-04-17 09:16:03 +00:00
}
2018-04-17 10:04:36 +00:00
// CustomMiddle func
2018-04-17 09:16:03 +00:00
type CustomMiddle func(*Context)
2018-04-17 10:04:36 +00:00
// PatchContext func
2018-04-18 06:16:29 +00:00
func PatchContext(handler func(*Context)) gin.HandlerFunc {
2018-04-17 09:16:03 +00:00
return func(c *gin.Context) {
ctx := &Context{
Context: c,
2018-04-18 06:16:29 +00:00
C: make(map[string]interface{}),
2018-04-17 09:16:03 +00:00
}
handler(ctx)
}
}
2018-04-18 06:16:29 +00:00
// BindData -
func (c *Context) BindData(i interface{}) error {
b := binding.Default(c.Request.Method, c.ContentType())
return c.ShouldBindWith(i, b)
}
2018-04-17 09:16:03 +00:00
// NotFound response
2018-04-17 10:04:36 +00:00
func (c *Context) NotFound(msg interface{}) {
2018-04-17 09:16:03 +00:00
obj := apimsg.GetRes("NotFound", msg)
2018-04-17 10:04:36 +00:00
c.AbortWithStatusJSON(obj.Status, obj.Obj)
}
// DataFormat error response
func (c *Context) DataFormat(msg interface{}) {
obj := apimsg.GetRes("DataFormat", msg)
2018-04-17 09:16:03 +00:00
c.AbortWithStatusJSON(obj.Status, obj.Obj)
}
// Success response
func (c *Context) Success(msg interface{}) {
obj := apimsg.GetRes("Success", msg)
2018-04-17 10:04:36 +00:00
c.AbortWithStatusJSON(obj.Status, obj.Obj)
}
// ServerError response
func (c *Context) ServerError(msg interface{}) {
obj := apimsg.GetRes("InternalError", msg)
c.AbortWithStatusJSON(obj.Status, obj.Obj)
}
// CustomRes send othen response
func (c *Context) CustomRes(name string, msg interface{}) {
obj := apimsg.GetRes(name, msg)
c.AbortWithStatusJSON(obj.Status, obj.Obj)
2018-04-17 09:16:03 +00:00
}