You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
103 lines
2.2 KiB
103 lines
2.2 KiB
package result
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
var (
|
|
Ok = NewResponse(WithCode(200), WithMsg("success"))
|
|
Created = NewResponse(WithCode(201), WithMsg("created"))
|
|
InvalidParams = NewResponse(WithCode(400), WithMsg("invalid params"))
|
|
Unauthorized = NewResponse(WithCode(401), WithMsg("unauthorized"))
|
|
Forbidden = NewResponse(WithCode(403), WithMsg("forbidden"))
|
|
NotFound = NewResponse(WithCode(404), WithMsg("not found"))
|
|
TooManyRequests = NewResponse(WithCode(429), WithMsg("too many requests"))
|
|
Wrong = NewResponse(WithCode(500), WithMsg("something wrong"))
|
|
)
|
|
|
|
type Response struct {
|
|
Code int `json:"code"`
|
|
Msg string `json:"msg"`
|
|
Data interface{} `json:"data"`
|
|
}
|
|
|
|
type ResponseOption func(*Response)
|
|
|
|
func NewResponse(options ...ResponseOption) *Response {
|
|
resp := &Response{}
|
|
for _, option := range options {
|
|
option(resp)
|
|
}
|
|
return resp
|
|
}
|
|
|
|
func (r *Response) WithCode(code int) *Response {
|
|
r.Code = code
|
|
return r
|
|
}
|
|
|
|
func (r *Response) WithMsg(msg string) *Response {
|
|
r.Msg = msg
|
|
return r
|
|
}
|
|
|
|
func (r *Response) WithData(data interface{}) *Response {
|
|
r.Data = data
|
|
return r
|
|
}
|
|
|
|
func (r *Response) WithFlag(flag interface{}) *Response {
|
|
r.Data = gin.H{"flag": flag}
|
|
return r
|
|
}
|
|
|
|
func (r *Response) WithValue(value interface{}) *Response {
|
|
r.Data = gin.H{"value": value}
|
|
return r
|
|
}
|
|
|
|
func (r *Response) WithFlagValue(flag interface{}, value interface{}) *Response {
|
|
r.Data = gin.H{"flag": flag, "value": value}
|
|
return r
|
|
}
|
|
|
|
func WithCode(code int) ResponseOption {
|
|
return func(resp *Response) {
|
|
resp.Code = code
|
|
}
|
|
}
|
|
|
|
func WithMsg(msg string) ResponseOption {
|
|
return func(resp *Response) {
|
|
resp.Msg = msg
|
|
}
|
|
}
|
|
|
|
func WithData(data interface{}) ResponseOption {
|
|
return func(resp *Response) {
|
|
resp.Data = data
|
|
}
|
|
}
|
|
|
|
func (r *Response) Response(c *gin.Context, httpCode int) {
|
|
c.JSON(httpCode, &r)
|
|
}
|
|
|
|
func (r *Response) Success(c *gin.Context) {
|
|
r.Response(c, http.StatusOK)
|
|
}
|
|
|
|
func (r *Response) Failure(c *gin.Context) {
|
|
r.Response(c, http.StatusOK)
|
|
}
|
|
|
|
func (r *Response) Error(c *gin.Context) {
|
|
r.Response(c, http.StatusInternalServerError)
|
|
}
|
|
|
|
func (r *Response) ToError() error {
|
|
return errors.New("code:" + strconv.Itoa(r.Code) + ", msg:" + r.Msg)
|
|
}
|
|
|