侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录
Go

beego笔记(4)之响应内容

zze
zze
2021-08-10 / 0 评论 / 0 点赞 / 401 阅读 / 2826 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

此系列我仅会记录一些 Beego 的基本使用以及常用语法,而不会对每个知识点详述,尽量做到以注释的形式让有 Web 开发经验的小伙伴一看就懂,也让自己在以后忘了某个语法或知识点的时候看到这里能迅速找回感觉~

package main

import (
	"encoding/xml"
	"github.com/beego/beego/v2/server/web"
)

type Demo2Controller struct {
	web.Controller
}

// 响应字符串
func (c *Demo2Controller) F1() {
	c.Ctx.WriteString("c.Ctx.WriteString()")
	/*
		响应:
			c.Ctx.WriteString()
	*/
}

// 响应字节
func (c *Demo2Controller) F2() {
	c.Ctx.Output.Body([]byte("c.Ctx.Output.Body()"))
	/*
		响应:
			c.Ctx.Output.Body()
	*/
}

// 响应模板文件,该模板的渲染实际也是使用 go template 完成,go template 的详细使用可参考 https://www.zze.xyz/archives/go-template.html 。
// 更多 beego 模板的详细使用可参考官方文档:https://beego.me/docs/mvc/view/tutorial.md。
func (c *Demo2Controller) F3() {
	// test.tpl 在 main.go 的同级 views 目录下
	// 若不指定 c.TplName 的值,则加载 views 目录下 <控制器全名称>/<Action 方法名称>.tpl 为模板,此处即为 demo2controller/f3.tpl
	c.TplName = "test.tpl"
	// 传入模板的数据
	c.Data["name"] = "zze"
	/*
		views/test.tpl:
			<h1>{{ .name }}</h1>
		响应:
			<h1>zze</h1>
	*/
}

// 响应 json
func (c *Demo2Controller) F4() {
	// map 的 Key 必须为 json
	c.Data["json"] = map[string]string{"a": "1", "b": "2"}
	c.ServeJSON()
	/*
		响应:
			{"a":"1","b":"2"}
	*/
}

// 响应 xml
func (c *Demo2Controller) F5() {
	// map 的 Key 必须为 xml,值不能是 map 类型,必须类型为 xml.Name、名为 XMLName 的属性
	c.Data["xml"] = struct {
		XMLName xml.Name `xml:"root"`
		Name    string   `xml:"name"`
		Age     int      `xml:"age"`
	}{Name: "zze", Age: 18}
	c.ServeXML()
	/*
		响应:
			<root><name>zze</name><age>18</age></root>
	*/
}

// 响应 yaml
func (c *Demo2Controller) F6() {
	// map 的 Key 必须为 yaml
	c.Data["yaml"] = map[string]string{"a": "1", "b": "2"}
	c.ServeYAML()
	/*
		响应:
			a: "1"
			b: "2"
	*/
}

// 响应重定向
func (c *Demo2Controller) F7() {
	c.Redirect("https://www.zze.xyz", 302)
	/*
		$ curl -I 127.0.0.1:8080/demo2/f7
		HTTP/1.1 302 Found
		Content-Type: text/html; charset=utf-8
		Location: https://www.zze.xyz
		Date: Mon, 09 Aug 2021 11:48:47 GMT
	*/
}

// 响应错误状态码
func (c *Demo2Controller) F8() {
	c.Abort("404")
	/*
		$ curl -I 127.0.0.1:8080/demo2/f8
		HTTP/1.1 404 Not Found
		Date: Mon, 09 Aug 2021 11:47:22 GMT
		Content-Length: 2000
		Content-Type: text/html; charset=utf-8
	*/
}

// 响应连接关闭
func (c *Demo2Controller) F9() {
	c.StopRun()
	/*
		HTTP/1.1 200 OK
		Date: Mon, 09 Aug 2021 11:51:13 GMT
		Content-Length: 0
		Connection: close
	*/
}

func main() {
	web.AutoRouter(&Demo2Controller{})
	web.Run()
}

0

评论区