first
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
package context
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
)
|
||||
|
||||
// Context -
|
||||
type Context struct {
|
||||
*gin.Context
|
||||
}
|
||||
|
||||
// CustomMiddleware -
|
||||
type CustomMiddleware func(*Context)
|
||||
|
||||
// PatchContext -
|
||||
func PatchContext(handle CustomMiddleware) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := &Context{
|
||||
Context: c,
|
||||
}
|
||||
handle(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func parseResponse(body interface{}) interface{} {
|
||||
switch body.(type) {
|
||||
case string:
|
||||
return map[string]interface{}{
|
||||
"message": body,
|
||||
}
|
||||
case map[string]interface{}:
|
||||
case map[string]string:
|
||||
return body
|
||||
default:
|
||||
return map[string]string{
|
||||
"message": "empty",
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// BindData client body data
|
||||
func (p *Context) BindData(i interface{}) error {
|
||||
b := binding.Default(p.Request.Method, p.ContentType())
|
||||
return p.ShouldBindWith(i, b)
|
||||
}
|
||||
|
||||
// Success -
|
||||
func (p *Context) Success(res ...interface{}) {
|
||||
var resBody interface{}
|
||||
if len(res) > 0 {
|
||||
resBody = parseResponse(res)
|
||||
} else {
|
||||
resBody = parseResponse("success")
|
||||
}
|
||||
p.AbortWithStatusJSON(http.StatusOK, resBody)
|
||||
}
|
||||
|
||||
// ClientError -
|
||||
func (p *Context) ClientError(res ...interface{}) {
|
||||
var resBody interface{}
|
||||
if len(res) > 0 {
|
||||
resBody = parseResponse(res)
|
||||
} else {
|
||||
resBody = parseResponse("bad request")
|
||||
}
|
||||
p.AbortWithStatusJSON(http.StatusBadRequest, resBody)
|
||||
}
|
||||
|
||||
// ServerError -
|
||||
func (p *Context) ServerError(res ...interface{}) {
|
||||
var resBody interface{}
|
||||
if len(res) > 0 {
|
||||
resBody = parseResponse(res)
|
||||
} else {
|
||||
resBody = parseResponse("internal error")
|
||||
}
|
||||
p.AbortWithStatusJSON(http.StatusInternalServerError, resBody)
|
||||
}
|
||||
|
||||
// CustomRes -
|
||||
func (p *Context) CustomRes(status int, res interface{}) {
|
||||
resBody := parseResponse(res)
|
||||
p.AbortWithStatusJSON(status, resBody)
|
||||
}
|
||||
Reference in New Issue
Block a user