Go Web
net/http library
package main
import (
"fmt"
"net/http"
)
func sayHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello")
}
func main() {
http.HandleFunc("/hello", sayHello)
err := http.ListenAndServe(":9090", nil)
if err != nil {
fmt.Println("http server failed, err:", err)
}
}
Start the service
go run main.go
access browser
http://localhost:9090/hello
http/template library
Template file hello.tmpl
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
<p>{{ . }}</p>
</body>
</html>
main.go
func sayHello(w http.ResponseWriter, r *http.Request) {
//解析模板
t, _ := template.ParseFiles("./hello.tmpl")
//渲染模板
t.Execute(w, "World")
}
func main() {
http.HandleFunc("/", sayHello)
http.ListenAndServe(":9091", nil)
}
Parametric rendering
t.Execute(w, map[string]interface{}{
"a": "aaa",//{{ .a }}
"b": "bbb",//{{ .b }}
})
Template comments
{{/* .a */}}
Conditional judgment
{{ if lt .a 1}}
a < 1
{{ else }}
a >= 1
{{ end }}
cycle
t.Execute(w, map[string]interface{}{
"num": []string{"a", "b", "c"},
})
{{ range $k,$v := .num}}
<p>{{ $k }} - {{ $v }}</p>
{{ else }}
---
{{ end }}
inherit
t, err := template.ParseFiles("./base.tmpl","./index.tmpl")
name := "AAA"
t.ExecuteTemplate(w, "index.tmpl", name)
base.tmpl
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>Go Templates</title>
</head>
<body>
<div class="container-fluid">
{{block "content" . }}{{end}}
</div>
</body>
</html>
index.tmpl
{{template "base.tmpl"}}
{{define "content"}}
<div>Hello world!</div>
{{end}}
Modify the identifier
template.New("index.tmpl").Delims("{[","]}").ParseFiles("./index.tmpl")
custom function
t, _ := template.New("xss.tmpl").Funcs(template.FuncMap{
"safe": func(s string) template.HTML {
return template.HTML(s)
},
}).ParseFiles("./xss.tmpl")
str := "<a>123</a>"
t.Execute(w, str)
sss.tmpl
{{ . | safe }}
Gin framework
installation and use
Configure the proxy
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
Introduce gin library
go get -u github.com/gin-gonic/gin
Write Demo
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run(":8081") // 监听并在 0.0.0.0:8081 上启动服务
}
Solution: no required module provides package github.com/gin-gonic/gin: go.mod file not found in current directory or any parent directory; see 'go help modules'
go mod init xxx
go get github.com/gin-gonic/gin
Solve the problem of red wavy lines in VSCODE:
go mod vendor
access browser
http://localhost:8081/ping
HTML rendering
In the Gin framework, use theLoadHTMLGlob()
orLoadHTMLFiles()
method for HTML template rendering.
main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// r.LoadHTMLGlob("template/**/*")
r.LoadHTMLFiles("template/user/index.html")
r.GET("/user/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "user/index.html", gin.H{
"title": "User Index",
})
})
r.Run(":8081") // 监听并在 0.0.0.0:8081 上启动服务
}
template/user/index.html
{{define "user/index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{.title}}</title>
</head>
<body>
{{.title}}
</body>
</html>
{{end}}
custom function
r.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML {
return template.HTML(str)
},
})
corresponding template
{{.link| safe}}
load static files
Load static files before parsing the file (LoadHTMLGlob)
r.Static("/xxx", "./statics") //以xxx开头的访问解析到./statics目录
template file
<link rel="stylesheet" href="xxx/index.css"/>
template inheritance
The Gin framework uses a single template by default. If you need to use theblock template
function, you can use the"github.com/gin-contrib/multitemplate"
library to achieve
go get -u github.com/gin-contrib/multitemplate
home.tmpl and index.tmpl inherit base.tmpl
templates
├── includes
│ ├── home.tmpl
│ └── index.tmpl
├── layouts
│ └── base.tmpl
load function
func loadTemplates(templatesDir string) multitemplate.Renderer {
r := multitemplate.NewRenderer()
layouts, err := filepath.Glob(templatesDir + "/layouts/*.tmpl")
if err != nil {
panic(err.Error())
}
includes, err := filepath.Glob(templatesDir + "/includes/*.tmpl")
if err != nil {
panic(err.Error())
}
// 为layouts/和includes/目录生成 templates map
for _, include := range includes {
layoutCopy := make([]string, len(layouts))
copy(layoutCopy, layouts)
files := append(layoutCopy, include)
r.AddFromFiles(filepath.Base(include), files...)
}
return r
}
func main() {
r := gin.Default()
r.HTMLRender = loadTemplates("./templates")
r.LoadHTMLGlob("templates/**/*")
r.GET("/ping", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", nil)
})
r.Run(":8082") // 监听并在 0.0.0.0:8081 上启动服务
}
Get the current program path
func getCurrentPath() string {
if ex, err := os.Executable(); err == nil {
return filepath.Dir(ex)
}
return "./"
}
JSON rendering
gin.H is short for map[string]interface{}
func main() {
r := gin.Default()
// 方式一:自己拼接JSON {"message":"Hello World"}
r.GET("/json", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "Hello World",
})
})
//方法二:使用结构体 {"name":"test"}
var msg struct {
Name string `json:"name"`
}
msg.Name = "test"
r.GET("/json2", func(c *gin.Context) {
c.JSON(http.StatusOK, msg)
})
r.Run(":8082") // 监听并在 0.0.0.0:8082 上启动服务
}
XML, YMAL, protobuf rendering
c.XML(http.StatusOK, msg)
c.YMAL(http.StatusOK, msg)
c.ProtoBuf(http.StatusOK, data)
Gin parameters
query parameter parsing
http://localhost:8082/web?query=xxx
func main() {
r := gin.Default()
r.GET("/web", func(c *gin.Context) {
// query := c.Query("query")
// query := c.DefaultQuery("query", "default")//设置默认值
query, ok := c.GetQuery("query") //ok表示是否获取到参数
if !ok {
query = "default"
}
c.JSON(http.StatusOK, gin.H{
"query": query,
})
})
r.Run(":8082")
}
form parameter parsing
login.html
func main() {
r := gin.Default()
r.LoadHTMLFiles("login.html")
r.GET("/login", func(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
})
r.POST("/login", func(c *gin.Context) {
// username := c.PostForm("username")
// password := c.PostForm("password") //取到值则返回,取不到返回空
// username := c.DefaultPostForm("username", "aaa")
// password := c.DefaultPostForm("password", "bbb") //默认值
username, ok := c.GetPostForm("username")
if !ok {
username = "xxx"
}
password, ok := c.GetPostForm("password")
if !ok {
password = "yyy"
}
c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
r.Run(":8082")
}
Json parameter parsing
func main() {
r := gin.Default()
r.POST("/json", func(c *gin.Context) {
body, _ := c.GetRawData()
var m gin.H //map[string] interface{}
_ = json.Unmarshal(body, &m) //Unmarshal时接收体必须传递指针
c.JSON(http.StatusOK, m)
})
r.Run(":8082")
}
Path parameter parsing
Access path: http://localhost:8082/itxiaoma/999
func main() {
r := gin.Default()
r.GET("/:name/:id", func(c *gin.Context) {
name := c.Param("name")
id := c.Param("id")
c.JSON(http.StatusOK, gin.H{
"name": name,
"id": id,
})
})
r.Run(":8082")
}
parameter binding
ShouldBind
will parse the data in the request in the following order to complete the binding:
- If it is a
GET
request, only use theForm
binding engine (query
). -
POST
请求,content-type
JSON
XML
,然后Form
(form-data
).
type Login struct {
Username string `form:"username" json:"user" binding:"required"`
Password string `form:"password" json:"pwd" binding:"required"`
}
func main() {
r := gin.Default()
r.POST("/get", func(c *gin.Context) {
var login Login
err := c.ShouldBind(&login)//自动解析query
if err == nil {
c.JSON(http.StatusOK, login)
}
})
r.POST("/login", func(c *gin.Context) {
var login Login
err := c.ShouldBind(&login)//自动解析json,form
if err == nil {
c.JSON(http.StatusOK, login)
}
})
r.Run(":8082")
}
File Upload
<form action="/upload" method="post" enctype="multipart/form-data">
<input name="filename" type="file"/>
<button type="submit">Submit</button>
</form>
single file upload
func main() {
r := gin.Default()
r.LoadHTMLFiles("upload.html")
r.GET("/upload", func(c *gin.Context) {
c.HTML(http.StatusOK, "upload.html", nil)
})
r.POST("/upload", func(c *gin.Context) {
//从请求中读取文件
file, _ := c.FormFile("filename")
//将文件保存到服务端
// filePath := fmt.Sprintf("./%s",file.Filename)
filePath := path.Join("./", file.Filename)
c.SaveUploadedFile(file, filePath)
c.JSON(http.StatusOK, gin.H{
"filePath": filePath,
})
})
r.Run(":8082")
}
Multiple file upload
func main() {
router := gin.Default()
// 处理multipart forms提交文件时默认的内存限制是32 MiB
// 可以通过下面的方式修改
// router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// Multipart form
form, _ := c.MultipartForm()
files := form.File["file"]
for index, file := range files {
log.Println(file.Filename)
dst := fmt.Sprintf("C:/tmp/%s_%d", file.Filename, index)
// 上传文件到指定的目录
c.SaveUploadedFile(file, dst)
}
c.JSON(http.StatusOK, gin.H{
"message": fmt.Sprintf("%d files uploaded!", len(files)),
})
})
router.Run()
}
request redirection
HTTP redirect
func main() {
r := gin.Default()
//301重定向
r.GET("/baidu", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com")
})
r.Run(":8082")
}
route redirection
func main() {
r := gin.Default()
r.GET("/a", func(c *gin.Context) {
c.Request.URL.Path = "/b"
r.HandleContext(c)
})
r.GET("/b", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
r.Run(":8082")
}
routing
normal route
r.GET("/index", func(c *gin.Context) {...})
r.POST("/add", func(c *gin.Context) {...})
r.PUT("/update", func(c *gin.Context) {...})
r.DELETE("/delete", func(c *gin.Context) {...})
//全部请求类型
r.Any("/all", func(c *gin.Context) {...})
//示例
func main() {
r := gin.Default()
r.Any("/all", func(c *gin.Context) {
switch c.Request.Method {
case http.MethodGet:
c.JSON(http.StatusOK, gin.H{"method": "GET"})
case http.MethodPost:
c.JSON(http.StatusOK, gin.H{"method": "POST"})
}
})
r.Run(":8082")
}
Route with no handler configured: 404
r.NoRoute(func(c *gin.Context) {
c.HTML(http.StatusNotFound, "views/404.html", nil)
})
Routing group r.Group
Routes with a common prefix are a routing group, and routing groups support nesting
func main() {
r := gin.Default()
userGroup := r.Group("/user")
{
userGroup.GET("/index1", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"route": "/user/index1"})
})
userGroup.GET("/index2", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"route": "/user/index2"})
})
subGroup := userGroup.Group("/sub")
{
subGroup.GET("/index3", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"route": "/user/sub/index3"})
})
}
}
r.Run(":8082")
}
middleware
Define middleware
Gin middleware must be of type gin.HandlerFunc
func m1() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next() // 调用该请求的剩余处理程序
// c.Abort() // 不调用该请求的剩余处理程序
cost := time.Since(start)
fmt.Println("Cost:", cost)
}
}
register middleware
Global registration
func main() {
r := gin.Default()
r.Use(m1())
r.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
r.Run(":8082")
}
Register individually
func m2() gin.HandlerFunc {
return func(c *gin.Context) {
c.Abort() // 不调用该请求的剩余处理程序
}
}
func main() {
r := gin.Default()
r.Use(m1())
r.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
r.GET("/index2", m2(), func(c *gin.Context) {
//以下内容不会输出
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
r.Run(":8082")
}
Component registration
shopGroup := r.Group("/shop", m1())
//或shopGroup.Use(m1())
{
shopGroup.GET("/index", func(c *gin.Context) {...})
...
}
register multiple
r.Use(m1, m2, m3(false))
Precautions
gin default middleware
gin.Default()
default uses Logger
and Recovery
middleware, where:
-
Logger
The middleware writes logs togin.DefaultWriter
even ifGIN_MODE=release
is configured. -
Recovery
middleware will recover anypanic
. If there is panic, a 500 response code will be written.
If you don't want to use the above two default middleware, you can use gin.New()
to create a new route without any default middleware.
Use goroutine in gin middleware
When starting a new goroutine
handler
, the original context (c *gin.Context) cannot be used, its read-only copy must be used ( c.Copy()
). (Otherwise it is very unsafe to be modified during operation)
go funcXX(c.Copy())
Running multiple services on multiple ports
package main
import (
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
)
var (
g errgroup.Group
)
func router01() http.Handler {
e := gin.New()
e.Use(gin.Recovery())
e.GET("/", func(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": http.StatusOK,
"error": "Welcome server 01",
},
)
})
return e
}
func router02() http.Handler {
e := gin.New()
e.Use(gin.Recovery())
e.GET("/", func(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": http.StatusOK,
"error": "Welcome server 02",
},
)
})
return e
}
func main() {
server01 := &http.Server{
Addr: ":8080",
Handler: router01(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
server02 := &http.Server{
Addr: ":8081",
Handler: router02(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
// 借助errgroup.Group或者自行开启两个goroutine分别启动两个服务
g.Go(func() error {
return server01.ListenAndServe()
})
g.Go(func() error {
return server02.ListenAndServe()
})
if err := g.Wait(); err != nil {
log.Fatal(err)
}
}
References
Gin Chinese documentation: https://gin-gonic.com/zh-cn/docs/
Web development based on gin framework and gorm: https://www.bilibili.com/video/BV1gJ411p7xC
Related blogs: https://www.liwenzhou.com/posts/Go/Gin_framework/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。