多种格式数据输出
背景:假如前端或者提供的接口必须以指定的格式传输
json格式:会设置 content-type 为 application/json
type TestController struct {
beego.Controller
}
type Person struct {
Id int
Name string
Gender string
}
func (g *TestController)Get() {
test_data := Person{Id:123,Name:"zhiliao",Gender:"男"}
g.Data["json"] = &test_data -----这里必须叫json,因为ServeJSON()解析json变量的
fmt.Println(test_data)
g.ServeJSON()
//g.TplName = "test.html"
}
xml格式:会设置 content-type 为 application/xml
test_data := Person{Id:123,Name:"zhiliao",Gender:"男"}
g.Data["xml"] = &test_data -----这里必须叫xml,同上
g.ServeXML()
jsonp格式:会设置 content-type 为 application/javascript
test_data := Person{Id:123,Name:"zhiliao",Gender:"男"}
g.Data["jsonp"] = &test_data -----这里必须叫jsonp,同上
g.ServeJSONP()
yaml格式:会以文件传输的方式,yaml就是键值对
test_data := Person{Id:123,Name:"zhiliao",Gender:"男"}
g.Data["yaml"] = &test_data
g.ServeYAML()
yaml格式:
student:
- name : "zhiliao"
- age : 18
teacher:
- name : "laowang"
-age : 38
addr: "市区"
说明:
1.大小写敏感
2.使用缩进表示层级关系
3.缩进不允许使用tab,只允许空格
4.缩进的空格数不重要,只要相同层级的元素左对齐即可
5.'#'表示注释
6.以 - 开头的行表示构成一个数组,支持多维数组