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{}: return body case map[string]string: return body default: return map[string]string{ "message": "empty", } } } // BindData client body data func (p *Context) BindData(i interface{}) error { b := binding.Default(p.Request.Method, p.ContentType()) return p.ShouldBindWith(i, b) } // HTML - func (p *Context) HTML(tmpl string, data interface{}) { p.Context.HTML(http.StatusOK, tmpl, data) p.Abort() } // Success - func (p *Context) Success(res ...interface{}) { var resBody interface{} if len(res) > 0 { resBody = parseResponse(res[0]) } 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[0]) } 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[0]) } 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) }