response

作者: JunChow520 | 来源:发表于2022-01-05 02:16 被阅读0次

    目标:使用Gin框架开发接口,返回响应结构封装,统一管理。

    $ mkdir response && cd response
    

    封装返回响应的字段结构

    $ vim response.go
    
    package response
    
    import (
        "encoding/json"
        "log"
    )
    
    type Response struct {
        Code int         `json:"code"`
        Msg  string      `json:"msg"`
        Data interface{} `json:"data"`
    }
    
    // Response 构造函数
    func response(code int, msg string) *Response {
        return &Response{
            Code: code,
            Msg:  msg,
            Data: nil,
        }
    }
    
    // WithMsg 追加响应消息
    func (t *Response) WithMsg(msg string) Response {
        return Response{
            Code: t.Code,
            Msg:  msg,
            Data: t.Data,
        }
    }
    
    // WithData 追加响应数据
    func (t *Response) WithData(data interface{}) Response {
        return Response{
            Code: t.Code,
            Msg:  t.Msg,
            Data: data,
        }
    }
    
    // Json 返回JSON格式的数据
    func (t *Response) Json() string {
        s := &struct {
            Code int         `json:"code"`
            Msg  string      `json:"msg"`
            Data interface{} `json:"data"`
        }{
            Code: t.Code,
            Msg:  t.Msg,
            Data: t.Data,
        }
        raw, err := json.Marshal(s)
        if err != nil {
            log.Println(err)
        }
        return string(raw)
    }
    

    封装通用错误代码

    $ vim error.go
    
    package response
    
    var (
        Ok  = response(200, "操作成功")
        Err = response(500, "操作失败")
    )
    

    封装系统级错误编码

    $ vim system.go
    
    package response
    
    //服务级错误
    var (
        ErrParam   = response(10001, "参数有误")
        ErrSign    = response(10002, "签名有误")
        ErrCaptcha = response(10003, "验证码错误")
        ErrPhone   = response(10004, "手机号码不合法")
    )
    

    封装用户模块编码

    $ vim user.go
    
    package response
    
    //模块级错误 - 用户模块
    var (
        ErrUserService = response(20001, "用户服务异常")
    )
    

    在Gin控制器中返回响应

    例如:以用户修改密码为例

    func (s *User) Password(c *gin.Context) {
        var err error
        var p request.Password
        var mu model.User
    
        if err = c.ShouldBindJSON(&p); err != nil {
            c.JSON(http.StatusOK, response.ErrParam)
            return
        }
    
        mu = model.User{}
        mu.UserName = p.UserName
        mu.Password = p.Password
        if err, _ = service.NewUser().Password(&mu, p.NewPassword); err != nil {
            c.JSON(http.StatusOK, response.Err)
            return
        }
    
        c.JSON(http.StatusOK, response.Ok)
    }
    

    相关文章

      网友评论

          本文标题:response

          本文链接:https://www.haomeiwen.com/subject/gfqhcrtx.html