Beego踩坑

问题1:

  • 问题描述

按照官方实例返回的json结果始终为 {},官方实例如下:

//官方案例
func (this *AddController) Get() {
    mystruct := { ... }
    this.Data["json"] = &mystruct
    this.ServeJSON()
}
  • 解决方法:

返回json可以按如下步骤:

  1. 创建返回结果的结果体
//1.返回结果的结构体
type Response struct {
    Code    int         `json:"code"`
    Msg     string      `json:"msg"`
    Data    []string    `json:"data"`
    Success bool        `json:"success"`
}
  1. 在对应的函数中,写入
u.Data["json"] = &Response{200, "账号或密码错误", []string{}, false}

3.调用ServeJSON方法

u.ServeJSON()
  • 示例:
//返回结果的结构体
type Response struct {
    Code    int         `json:"code"`
    Msg     string      `json:"msg"`
    Data    []string    `json:"data"`
    Success bool        `json:"success"`
}
//返回结果的方法
// @Title Login
// @Description Logs user into the system
// @Param   username        query   string  true        "The username for login"
// @Param   password        query   string  true        "The password for login"
// @Success 200 {string} login success
// @Failure 403 user not exist
// @router /login [get]
func (u *UserController) Login() {
    username := u.GetString("username")
    password := u.GetString("password")
    u.Data["json"] = &Response{200, "账号或密码错误", []string{}, false}
    if models.Login(username, password) {
        u.Data["json"] = &Response{200, "登录成功", []string{}, true}
    }
    u.ServeJSON()
}

猜你喜欢

转载自blog.csdn.net/weixin_34216036/article/details/87123229
今日推荐