Beego脱坑(七)——多种格式数据输出

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yang731227/article/details/82287084
  • 直接输出 

直接输出我们前面一直在用,通过beego.Controller.Ctx.WriteString()方法可以直接向http response body中输出字符串。

例如:

this.Ctx.WriteString("hello world")
  •  模板输出

静态模板输出

静态模板输出,就是通过TplName指定简单的模板文件,讲html或者tpl文件直接输出到浏览器

静态模板:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Hello World!</h1>
</body>
</html>

路由注册:

 beego.Router("/hello",&controllers.HWControllers{})

 控制器代码:

package controllers

import "github.com/astaxie/beego"

type HWControllers struct {
	beego.Controller
}

func (this *HWControllers) Get() {
	this.TplName ="hello.html"
}

输出结果:

动态模板输出

在web中大部分的内容是静态的,只有少部分数据是动态的。为了复用模板的代码,需要能够把动态的数据插入到模板中,这需要特出的语法。

beego中模板通过{{}}包含需要被替换的字段,同时需要把要替换的内容添加到Controller的Data中,这样Controller执行时会自动匹配渲染模板。

静态模板:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>你猜我会输出什么:{{.HW}}</h1>
</body>
</html>

路由注册:

 beego.Router("/hello",&controllers.HWControllers{})

 控制器代码:

package controllers

import "github.com/astaxie/beego"

type HWControllers struct {
	beego.Controller
}

func (this *HWControllers) Get() {
	this.Data["HW"] ="Hello  World"
	this.TplName ="hello.html"
}

我们只是简单的修改了下上面的代码。现在来看看输出结果:

beego 当初设计的时候就考虑了 API 功能的设计,而我们在设计 API 的时候经常是输出 JSON 或者 XML 数据,那么 beego 提供了这样的方式直接输出:

特别注意的一个坑点,如果是想要把结构体作为输出对象,以属性名一定要大写。因为go的首字母大写代表为pubic属性。

我们先定义User一个结构体,为下面两种输出方式使用

type User struct {
	Name string  //首字母一定要大写
	Age  int
	Sex  string	
}
  • json格式数据输出

func (this *ApiController) Get(){
	user:= &User{"yj",20,"m"}
	this.Data["json"] =user  
	this.ServeJSON()
}

 调用 ServeJSON 之后,会设置 content-type 为 application/json,然后同时把数据进行 JSON 序列化输出。 

输出结果:

  • XML格式数据输出

func (this *ApiController) XmlFunc(){

	user:= &User{"yj",20,"m"}
	this.Data["xml"] =user
	this.ServeXML()
}

调用 ServeXML 之后,会设置 content-type 为 application/xml,同时数据会进行 XML 序列化输出。 

输出结果:

猜你喜欢

转载自blog.csdn.net/yang731227/article/details/82287084