Go 入门指南 Go 入门指南
文档 GitHub
译者 GitHub
文档 GitHub
译者 GitHub
  • 前言
  • 学习 Go 语言

    • 第1章:Go 语言的起源,发展与普及

      • 1.1 起源与发展
      • 1.2 语言的主要特性与发展的环境和影响因素
    • 第2章:安装与运行环境

      • 2.1 平台与架构
      • 2.2 Go 环境变量
      • 2.3 在 Linux 上安装 Go
      • 2.4 在 Mac OS X 上安装 Go
      • 2.5 在 Windows 上安装 Go
      • 2.6 安装目录清单
      • 2.7 Go 运行时 (runtime)
      • 2.8 Go 解释器
    • 第3章:编辑器、集成开发环境与其它工具

      • 3.1 Go 开发环境的基本要求
      • 3.2 编辑器和集成开发环境
      • 3.3 调试器
      • 3.4 构建并运行 Go 程序
      • 3.5 格式化代码
      • 3.6 生成代码文档
      • 3.7 其它工具
      • 3.8 Go 性能说明
      • 3.9 与其它语言进行交互
  • 语言的核心结构与技术

    • 第4章:基本结构和基本数据类型

      • 4.1 文件名、关键字与标识符
      • 4.2 Go 程序的基本结构和要素
      • 4.3 常量
      • 4.4 变量
      • 4.5 基本类型和运算符
      • 4.6 字符串
      • 4.7 strings 和 strconv 包
      • 4.8 时间和日期
      • 4.9 指针
    • 第5章:控制结构
      • 5.1 if-else 结构
      • 5.2 测试多返回值函数的错误
      • 5.3 switch 结构
      • 5.4 for 结构
      • 5.5 break 与 continue
      • 5.6 标签与 goto
    • 第6章:函数(function)
      • 6.1 介绍
      • 6.2 函数参数与返回值
      • 6.3 传递变长参数
      • 6.4 defer 和追踪
      • 6.5 内置函数
      • 6.6 递归函数
      • 6.7 将函数作为参数
      • 6.8 闭包
      • 6.9 应用闭包:将函数作为返回值
      • 6.10 使用闭包调试
      • 6.11 计算函数执行时间
      • 6.12 通过内存缓存来提升性能
    • 第7章:数组与切片
      • 7.1 声明和初始化
      • 7.2 切片
      • 7.3 For-range 结构
      • 7.4 切片重组 (reslice)
      • 7.5 切片的复制与追加
      • 7.6 字符串、数组和切片的应用
    • 第8章:Map
      • 8.1 声明、初始化和 make
      • 8.2 测试键值对是否存在及删除元素
      • 8.3 for-range 的配套用法
      • 8.4 map 类型的切片
      • 8.5 map 的排序
      • 8.6 将 map 的键值对调
    • 第9章:包(package)
      • 9.1 标准库概述
      • 9.2 regexp 包
      • 9.3 锁和 sync 包
      • 9.4 精密计算和 big 包
      • 9.5 自定义包和可见性
      • 9.6 为自定义包使用 godoc
      • 9.7 使用 go install 安装自定义包
      • 9.8 自定义包的目录结构、go install 和 go test
      • 9.9 通过 Git 打包和安装
      • 9.10 Go 的外部包和项目
      • 9.11 在 Go 程序中使用外部库
    • 第10章:结构(struct)与方法(method)

      • 10.1 结构体定义
      • 10.2 使用工厂方法创建结构体实例
      • 10.3 使用自定义包中的结构体
      • 10.4 带标签的结构体
      • 10.5 匿名字段和内嵌结构体
      • 10.6 方法
      • 10.7 类型的 String() 方法和格式化描述符
      • 10.8 垃圾回收和 SetFinalizer
    • 第11章:接口(interface)与反射(reflection)

      • 11.1 接口是什么
      • 11.2 接口嵌套接口
      • 11.3 类型断言:如何检测和转换接口变量的类型
      • 11.4 类型判断:type-switch
      • 11.5 测试一个值是否实现了某个接口
      • 11.6 使用方法集与接口
      • 11.7 第一个例子:使用 Sorter 接口排序
      • 11.8 第二个例子:读和写
      • 11.9 空接口
      • 11.10 反射包
      • 11.11 Printf() 和反射
      • 11.12 接口与动态类型
      • 11.13 总结:Go 中的面向对象
      • 11.14 结构体、集合和高阶函数
  • Go 高级编程

    • 第12章:读写数据

      • 12.1 读取用户的输入
      • 12.2 文件读写
      • 12.3 文件拷贝
      • 12.4 从命令行读取参数
      • 12.5 用 buffer 读取文件
      • 12.6 用切片读写文件
      • 12.7 用 defer 关闭文件
      • 12.8 使用接口的实际例子:fmt.Fprintf
      • 12.9 JSON 数据格式
      • 12.10 XML 数据格式
      • 12.11 用 Gob 传输数据
      • 12.12 Go 中的密码学
    • 第13章:错误处理与测试

      • 13.1 错误处理
      • 13.2 运行时异常和 panic
      • 13.3 从 panic 中恢复 (recover)
      • 13.4 自定义包中的错误处理和 panicking
      • 13.5 一种用闭包处理错误的模式
      • 13.6 启动外部命令和程序
      • 13.7 Go 中的单元测试和基准测试
      • 13.8 测试的具体例子
      • 13.9 用(测试数据)表驱动测试
      • 13.10 性能调试:分析并优化 Go 程序
    • 第14章:协程 (goroutine) 与通道 (channel)

      • 14.1 并发、并行和协程
      • 14.2 协程间的信道
      • 14.3 协程的同步:关闭通道-测试阻塞的通道
      • 14.4 使用 select 切换协程
      • 14.5 通道、超时和计时器(Ticker)
      • 14.6 协程和恢复 (recover)
      • 14.7 新旧模型对比:任务和 worker
      • 14.8 惰性生成器的实现
      • 14.9 实现 Futures 模式
      • 14.10 复用
      • 14.11 限制同时处理的请求数
      • 14.12 链式协程
      • 14.13 在多核心上并行计算
      • 14.14 并行化大量数据的计算
      • 14.15 漏桶算法
      • 14.16 对 Go 协程进行基准测试
      • 14.17 使用通道并发访问对象
    • 第 15 章:网络、模板与网页应用

      • 15.1 tcp 服务器
      • 15.2 一个简单的 web 服务器
      • 15.3 访问并读取页面数据
      • 15.4 写一个简单的网页应用
      • 15.5 确保网页应用健壮
      • 15.6 用模板编写网页应用
      • 15.7 探索 template 包
      • 15.8 精巧的多功能网页服务器
      • 15.9 用 rpc 实现远程过程调用
      • 15.10 基于网络的通道 netchan
      • 15.11 与 websocket 通信
      • 15.12 用 smtp 发送邮件
  • 实际应用

    • 第16章:常见的陷阱与错误

      • 16.1 误用短声明导致变量覆盖
      • 16.2 误用字符串
      • 16.3 发生错误时使用 defer 关闭一个文件
      • 16.4 何时使用 new() 和 make()
      • 16.5 不需要将一个指向切片的指针传递给函数
      • 16.6 使用指针指向接口类型
      • 16.7 使用值类型时误用指针
      • 16.8 误用协程和通道
      • 16.9 闭包和协程的使用
      • 16.10 糟糕的错误处理
    • 第17章:模式

      • 17.1 逗号 ok 模式
      • 17.2 defer 模式
      • 17.3 可见性模式
      • 17.4 运算符模式和接口
    • 第18章:出于性能考虑的实用代码片段

      • 18.1 字符串
      • 18.2 数组和切片
      • 18.3 映射
      • 18.4 结构体
      • 18.5 接口
      • 18.6 函数
      • 18.7 文件
      • 18.8 协程 (goroutine) 与通道 (channel)
      • 18.9 网络和网页应用
      • 18.10 其他
      • 18.11 出于性能考虑的最佳实践和建议
    • 第19章:构建一个完整的应用程序

      • 19.1 简介
      • 19.2 短网址项目简介
      • 版本 1 - 数据结构和前端界面
      • 19.4 用户界面:web 服务端
      • 版本 2 - 添加持久化存储
      • 版本 3 - 添加协程
      • 版本 4 - 用 JSON 持久化存储
      • 版本 5 - 分布式程序
      • 19.9 使用代理缓存
      • 19.10 总结和增强
    • 第20章:Go 语言在 Google App Engine 的使用

      • 20.1 什么是 Google App Engine?
      • 20.2 云上的 Go
      • 20.3 安装 Go App Engine SDK:为 Go 部署的开发环境
      • 20.4 建造你自己的 Hello world 应用
      • 20.5 使用用户服务和探索其 API
      • 20.6 处理窗口
      • 20.7 使用数据存储
      • 20.8 上传到云端
    • 第21章:实世界中 Go 的使用

      • 21.1 Heroku:一个使用 Go 的高度可用一致数据存储
      • 21.2 MROffice:一个使用 Go 的呼叫中心网络电话 (VOIP) 系统
      • 21.3 Atlassian:一个虚拟机群管理系统
      • 21.4 Camilistore:一个可寻址内容存储系统
      • 21.5 Go 语言的其他应用

15.7 探索 template 包

(template 包的文档可以在 https://golang.org/pkg/text/template/ 找到。)

在前一章节,我们使用 template 对象把数据结构整合到 HTML 模板中。这项技术确实对网页应用程序非常有用,然而模板是一项更为通用的技术方案:数据驱动的模板被创建出来,以生成文本输出。HTML 仅是其中的一种特定使用案例。

模板通过与数据结构的整合来生成,通常为结构体或其切片。当数据项传递给 tmpl.Execute() ,它用其中的元素进行替换, 动态地重写某一小段文本。只有被导出的数据项才可以被整合进模板中。可以在 {{ 和 }} 中加入数据求值或控制结构。数据项可以是值或指针,接口隐藏了他们的差异。

15.7.1 字段替换:{{.FieldName}}

要在模板中包含某个字段的内容,使用双花括号括起以点 (.) 开头的字段名。例如,假设 Name 是某个结构体的字段,其值要在被模板整合时替换,则在模板中使用文本 {{.Name}}。当 Name 是 map 的键时这么做也是可行的。要创建一个新的 Template 对象,调用 template.New(),其字符串参数可以指定模板的名称。正如 15.5 节出现过的,Parse() 方法通过解析模板定义字符串,生成模板的内部表示。当使用包含模板定义字符串的文件时,将文件路径传递给 ParseFiles() 来解析。解析过程如产生错误,这两个函数第二个返回值 error != nil。最后通过 Execute() 方法,数据结构中的内容与模板整合,并将结果写入方法的第一个参数中,其类型为 io.Writer。再一次地,可能会有 error 返回。以下程序演示了这些步骤,输出通过 os.Stdout() 被写到控制台。

示例 15.13 template_field.go

package main

import (
	"fmt"
	"os"
	"text/template"
)

type Person struct {
	Name string
	nonExportedAgeField string
}

func main() {
	t := template.New("hello")
	t, _ = t.Parse("hello {{.Name}}!")
	p := Person{Name: "Mary", nonExportedAgeField: "31"}
	if err := t.Execute(os.Stdout, p); err != nil {
		fmt.Println("There was an error:", err.Error())
	}
}

输出:hello Mary!

如果数据结构中包含一个未导出的字段,当我们尝试把它整合到类似这样的定义字符串:

t, _ = t.Parse("your age is {{.nonExportedAgeField}}!")

会产生错误:

There was an error: template: nonexported template hello:1: can’t evaluate field nonExportedAgeField in type main.Person.

如果只是想简单地把 Execute() 方法的第二个参数用于替换,使用 {{.}}。

当在浏览器环境中进行这些步骤,应首先使用 html 过滤器来过滤内容,例如 {{html .}}, 或者对 FieldName 过滤:{{ .FieldName |html }}。

|html 这部分代码,是请求模板引擎在输出 FieldName 的结果前把值传递给 html 格式化器,它会执行 HTML 字符转义(例如把 > 替换为 >)。这可以避免用户输入数据破坏 HTML 文档结构。

15.7.2 验证模板格式

为了确保模板定义语法是正确的,使用 Must() 函数处理 Parse 的返回结果。在下面的例子中 tOK 是正确的模板, tErr 验证时发生错误,会导致运行时 panic。

示例 15.14 template_validation.go

package main

import (
	"text/template"
	"fmt"
)

func main() {
	tOk := template.New("ok")
	//a valid template, so no panic with Must:
	template.Must(tOk.Parse("/* and a comment */ some static text: {{ .Name }}"))
	fmt.Println("The first one parsed OK.")
	fmt.Println("The next one ought to fail.")
	tErr := template.New("error_template")
	template.Must(tErr.Parse(" some static text {{ .Name }"))
}

输出:

The first one parsed OK.
The next one ought to fail.
panic: template: error_template:1: unexpected "}" in operand

模板语法出现错误比较少见,可以使用 13.3节 概括的 defer/recover 机制来报告并纠正错误。

在代码中常见到这 3 个基本函数被串联使用:

var strTempl = template.Must(template.New("TName").Parse(strTemplateHTML))

练习 15.7 template_validation_recover.go

在上述示例代码上实现 defer/recover 机制。

15.7.3 If-else

运行 Execute() 产生的结果来自模板的输出,它包含静态文本,以及被 {{}} 包裹的称之为管道的文本。例如,运行这段代码(示例 15.15 pipline1.go):

t := template.New("template test")
t = template.Must(t.Parse("This is just static text. \n{{\"This is pipeline data - because it is evaluated within the double braces.\"}} {{`So is this, but within reverse quotes.`}}\n"))
t.Execute(os.Stdout, nil)

输出结果为:

This is just static text.
This is pipeline data—because it is evaluated within the double braces. So is this, but within reverse quotes.

现在我们可以对管道数据的输出结果用 if-else-end 设置条件约束:如果管道是空的,类似于:

{{if ``}} Will not print. {{end}}

那么 if 条件的求值结果为 false,不会有输出内容。但如果是这样:

{{if `anything`}} Print IF part. {{else}} Print ELSE part.{{end}}

会输出 Print IF part.。以下程序演示了这点:

示例 15.16 template_ifelse.go

package main

import (
	"os"
	"text/template"
)

func main() {
	tEmpty := template.New("template test")
	tEmpty = template.Must(tEmpty.Parse("Empty pipeline if demo: {{if ``}} Will not print. {{end}}\n")) //empty pipeline following if
	tEmpty.Execute(os.Stdout, nil)

	tWithValue := template.New("template test")
	tWithValue = template.Must(tWithValue.Parse("Non empty pipeline if demo: {{if `anything`}} Will print. {{end}}\n")) //non empty pipeline following if condition
	tWithValue.Execute(os.Stdout, nil)

	tIfElse := template.New("template test")
	tIfElse = template.Must(tIfElse.Parse("if-else demo: {{if `anything`}} Print IF part. {{else}} Print ELSE part.{{end}}\n")) //non empty pipeline following if condition
	tIfElse.Execute(os.Stdout, nil)
}

输出:

Empty pipeline if demo:
Non empty pipeline if demo: Will print.
if-else demo: Print IF part.

15.7.4 点号和 with-end

点号 (.) 可以在 Go 模板中使用:其值 {{.}} 被设置为当前管道的值。

with 语句将点号设为管道的值。如果管道是空的,那么不管 with-end 块之间有什么,都会被忽略。在被嵌套时,点号根据最近的作用域取得值。以下程序演示了这点:

示例 15.17 template_with_end.go

package main

import (
	"os"
	"text/template"
)

func main() {
	t := template.New("test")
	t, _ = t.Parse("{{with `hello`}}{{.}}{{end}}!\n")
	t.Execute(os.Stdout, nil)

	t, _ = t.Parse("{{with `hello`}}{{.}} {{with `Mary`}}{{.}}{{end}}{{end}}!\n")
	t.Execute(os.Stdout, nil)
}

输出:

hello!
hello Mary!

15.7.5 模板变量 $

可以在模板内为管道设置本地变量,变量名以 $ 符号作为前缀。变量名只能包含字母、数字和下划线。以下示例使用了多种形式的有效变量名。

示例 15.18 template_variables.go

package main

import (
	"os"
	"text/template"
)

func main() {
	t := template.New("test")
	t = template.Must(t.Parse("{{with $3 := `hello`}}{{$3}}{{end}}!\n"))
	t.Execute(os.Stdout, nil)

	t = template.Must(t.Parse("{{with $x3 := `hola`}}{{$x3}}{{end}}!\n"))
	t.Execute(os.Stdout, nil)

	t = template.Must(t.Parse("{{with $x_1 := `hey`}}{{$x_1}} {{.}} {{$x_1}}{{end}}!\n"))
	t.Execute(os.Stdout, nil)
}

输出:

hello!
hola!
hey hey hey!

15.7.6 range-end

range-end 结构格式为:{{range pipeline}} T1 {{else}} T0 {{end}}。

range 被用于在集合上迭代:管道的值必须是数组、切片或 map。如果管道的值长度为零,点号的值不受影响,且执行 T0;否则,点号被设置为数组、切片或 map 内元素的值,并执行 T1。

如果模板为:

{{range .}}
{{.}}
{{end}}

那么执行代码:

s := []int{1,2,3,4}
t.Execute(os.Stdout, s)

会输出:

1
2
3
4

如需更实用的示例,请参考 20.7 节,来自 App Engine 数据库的数据通过模板来显示:

{{range .}}
	{{with .Author}}
		<p><b>{{html .}}</b> wrote:</p>
	{{else}}
		<p>An anonymous person wrote:</p>
	{{end}}
	<pre>{{html .Content}}</pre>
	<pre>{{html .Date}}</pre>
{{end}}

这里 range . 在结构体切片上迭代,每次都包含 Author、Content 和 Date 字段。

15.7.7 模板预定义函数

也有一些可以在模板代码中使用的预定义函数,例如 printf() 函数工作方式类似于 fmt.Sprintf():

示例 15.19 predefined_functions.go

package main

import (
	"os"
	"text/template"
)

func main() {
	t := template.New("test")
	t = template.Must(t.Parse("{{with $x := `hello`}}{{printf `%s %s` $x `Mary`}}{{end}}!\n"))
	t.Execute(os.Stdout, nil)
}

输出 hello Mary!。

预定义函数也在 15.6 节中使用:{{ printf "%s" .Body|html}},否则字节切片 Body 会作为数字序列打印出来。

链接

  • 目录
  • 上一节:用模板编写网页应用
  • 下一节:精巧的多功能网页服务器
Last Updated:
Contributors: Mr.Fang
Prev
15.6 用模板编写网页应用
Next
15.8 精巧的多功能网页服务器