gin 自定义成功失败response输出

gin框架,自定义成功返回,错误返回输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package response

import (
"github.com/gin-gonic/gin"
"net/http"
)

type SuccessResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}


func SuccessRsp(ctx *gin.Context, data interface{}) {
res := SuccessResponse{
Code: 0,
Msg: "success",
Data: data,
}
ctx.JSON(http.StatusOK, res)
}
type Error struct {
HttpCode int `json:"-"`
Code int `json:"code"` // 这个是业务层的错误号,非Http Status Code
Msg interface{} `json:"msg"`

}
type Response struct {
Error *Error
Data interface{} `json:"data"`
}
func ErrorRsp(c *gin.Context, rsp *Response) {
if rsp.Error!=nil {
c.JSON(rsp.Error.HttpCode, rsp.Error)
return
}
c.JSON(rsp.Error.HttpCode,rsp.Data)
}
1
2
3
4
5
if ptype == "" {
response.ErrorRsp(c,&response.Response{Error: &response.Error{HttpCode: 200,Code: 400000,Msg: "参数输入错误!"},Data: ""})
}else{
response.SuccessRsp(c,ptype)
}