我是 beego 的新手,试图在路由上获取 JSON 响应。
我有一个这样定义的 Controller 。
package controllers
import (
"github.com/astaxie/beego"
)
type ErrorController struct {
beego.Controller
}
type ErrorJson struct {
s string
d string
}
func (this *ErrorController) Get() {
var responseJson ErrorJson
responseJson = ErrorJson{
s: "asdf",
d: "qwer",
}
this.Data["json"] = responseJson
this.ServeJson()
}
我的路由器定义为
beego.Router("/api", &controllers.ErrorController{})
当我访问路由时,我得到一个没有任何属性的空 JSON 对象。
{}
如果我用字符串替换 json 结构,我会得到响应。所以beego是知道 Controller 和方法的。
this.Data["json"] = "Hello World"
我做错了什么?
最佳答案
您需要export ErrorJson 中的字段,名称以大写字符开头。使用字段标签指定输出中的小写名称。
type ErrorJson struct {
S string `json:"s"`
D string `json:"d"`
}
encoding/json 包和类似的包会忽略未导出的字段。
关于Beego Controller 中的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34127023/