本文是李文周的博客go语言学习之路的目录提要版,方便复习查看使用,原文参见文章连接:
https://www.liwenzhou.com/posts/Go/go_menu/
不写测试的开发不是好程序员。我个人非常崇尚TDD(Test Driven Development)的,然而可惜的是国内的程序员都不太关注测试这一部分。 这篇文章主要介绍下在Go语言中如何做单元测试和基准测试。
web总结
http搭建简单的server
func sayHello(w http.ResponseWriter, r *http.Request) {
b, _ :=ioutil.ReadFile("./hello.txt") // ioutil读取当前目录下的hello.txt文件,
fmt.Fprintln(w, string(b))// 写出到浏览器
}
func main() {
http.HandleFunc("/hello", sayHello) //当url为hello时,执行sayHello函数
err := http.ListenAndServe(":9090", nil) //本机服务器的端口9090,
if err != nil {
fmt.Printf("http server failed, err:%v\n", err)
return
}
}
// hello.txt内容
<h1 style="color:orange">hello world</h1>
<h2>hello yzy</h2>
gin
下载gin
会下载到goPath的package中,前面的github/com/gin-gonic为其目录结构
go get -u github.com/gin-gonic/gin
第一个gin示例
// 导入gin包
import (
"github.com/gin-gonic/gin"
)
func sayHello(context *gin.Context) {
// 将json格式的内容写出,200是状态码,H是一个map
context.JSON(200, gin.H{
"message": "hello world",
})
}
func main(){
r:=gin.Default()// 创建一个默认的路由引擎
r.GET("/hello",sayHello) // get请求,路径/hello,执行函数sayHello
r.Run() //启动http服务,默认在127.0.0.1:8080开启服务
}
RESTful API
REST是Representational State Transfer的简称,中文翻译为“表征状态转移”或“表现层状态转化”。
简单来说,REST的含义就是客户端与Web服务器之间进行交互的时候,使用HTTP协议中的4个请求方法代表不同的动作。
GET
用来获取资源POST
用来新建资源PUT
用来更新资源DELETE
用来删除资源。
例如,我们现在要编写一个管理书籍的系统,我们可以查询对一本书进行查询、创建、更新和删除等操作,我们在编写程序的时候就要设计客户端浏览器与我们Web服务端交互的方式和路径。按照经验我们通常会设计成如下模式:
请求方法 | URL | 含义 |
---|---|---|
GET | /book | 查询书籍信息 |
POST | /create_book | 创建书籍记录 |
POST | /update_book | 更新书籍信息 |
POST | /delete_book | 删除书籍信息 |
同样的需求我们按照RESTful API设计如下:
请求方法 | URL | 含义 |
---|---|---|
GET | /book | 查询书籍信息 |
POST | /book | 创建书籍记录 |
PUT | /book | 更新书籍信息 |
DELETE | /book | 删除书籍信息 |
Gin框架支持开发RESTful API的开发。
func main() {
r := gin.Default()
r.GET("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "GET",
})
})
r.POST("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "POST",
})
})
r.PUT("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "PUT",
})
})
r.DELETE("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "DELETE",
})
})
}
Gin渲染
html渲染
Gin框架中使用LoadHTMLGlob()
或者LoadHTMLFiles()
方法进行HTML模板渲染。
func main() {
r := gin.Default() //获取路由引擎
r.LoadHTMLGlob("templates/**/*") // 加载html路径
//r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")
r.GET("/posts/index", func(c *gin.Context) {
//访问路径
c.HTML(http.StatusOK, "posts/index.html", gin.H{
// 状态码和模板引擎
"title": "posts/index", // 传动到前端的参数
})
})
r.GET("users/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.html", gin.H{
"title": "users/index",
})
})
r.Run(":8080")
}
自定义模板函数
func main() {
router := gin.Default()
router.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML{
return template.HTML