没志青年
发布于 2025-11-16 / 30 阅读
0

GIN 框架

参考文档:

https://gin-gonic.com/zh-cn/docs/examples/

https://gin-gonic.com/zh-cn/docs/

开发环境搭建

环境配置

1、安装go语言

下载地址:All releases - The Go Programming Language

选择 [ Linux x86-64 ] 的版本

2、添加环境变量

sudo vim ~/.bashrc

添加

GOROOT GO的安装目录

GOPATH 工作空间目录

PATH GO安装目录下的bin目录

# GO 环境配置
export PATH=$PATH:/home/hltj/imx6ull/go/bin
export GOPATH=/home/hltj/imx6ull/go_workplace
export GOROOT=/home/hltj/imx6ull/go
# GO 加速下载镜像
export GOPROXY=https://mirrors.aliyun.com/goproxy/,direct
# export GOPROXY=https://goproxy.cn,direct
source ~/.bashrc

验证

go version

项目搭建

在GO的工作目录下

1、创建项目目录

mkdir go_project
cd go_project
go mod init my_gin_project  这是项目的名字

会生成go.mod文件

go get -u github.com/gin-gonic/gin

// 如果手动在mod文件中删除或添加了依赖,需要更新

 // go update

示例代码 main.go

package main
​
import (
    "github.com/gin-gonic/gin"
)
​
func main() {
    r := gin.Default()
    r.GET("/", func(c *gin.Context) {
        c.String(200, "Hello, Gin!")
    })
    r.Run(":8080")
}
​

运行项目

go run main.go

普通编译

1、如果只有一个 main.go 文件

go build main.go

2、项目下有多个go文件(保证有一个main.go文件)

go build

3、指定生成的可执行文件的名字

go build -o abc

4、编译特定的 Go 文件

go build path/to/file.go

交叉编译

指定环境变量就行了,这个只在当前终端内生效。

export GOARCH=arm
export GOOS=linux
export CC=arm-linux-gnueabihf-gcc
export CGO_ENABLED=1

编译和上面一样

程序后台运行

nohup ./main > output.log 2>&1 &

使用jobs命令可以查看

获取参数

query参数

路径参数

json参数

返回数据

返回Json

返回xml

返回Html

使用 LoadHTMLGlob() 或者 LoadHTMLFiles() 返回HTML页面

router.LoadHTMLGlob("templates/*")
    //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "Main website",
        })
    })

麻烦的一种写法

func main() {
    tmpl := template.Must(template.ParseFiles("templates/users/index.tmpl"))
​
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        data := map[string]string{
            "title": "Hello, World!",
        }
        tmpl.ExecuteTemplate(w, "users/index.tmpl", data)
    })
​
    http.ListenAndServe(":8080", nil)
}

HTML渲染语法

HTML文件必须在 templates 目录下,且通常以 tmpl 作为文件后缀,这个可以修改的。

单个tmpl文件的格式

<html>
    <h1>
        {{ .title }}
    </h1>
</html>

若是在不同目录下存在名称相同的模板,那么文件的格式变为

templates/posts/index.tmpl

{{ define "posts/index.tmpl" }}
<html><h1>
    {{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}

templates/users/index.tmpl

{{ define "users/index.tmpl" }}
<html><h1>
    {{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}

代码

router.LoadHTMLGlob("templates/**/*")
    router.GET("/posts/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
            "title": "Posts",
        })
    })
    router.GET("/users/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
            "title": "Users",
        })
    })

变量

{{ .变量名 }}

条件判断

{{ if .isAdmin }}
<p>Welcome, admin!</p>
{{ else }}
<p>Welcome, user!</p>
{{ end }}

循环

<ul>
  {{ range .users }}
  <li>{{ . }}</li>
  {{ end }}
</ul>
data := map[string]interface{}{
    "title": "User List",
    "users": []string{"Alice", "Bob", "Charlie"},
}

模板嵌套

你可以在一个模板中包含其他模板,这对于模板的重用非常有用

{{ define "base.tmpl" }}
<html>
  <head>
    <title>{{ .title }}</title>
  </head>
  <body>
    {{ template "content" . }}
  </body>
</html>
{{ end }}
​
​
// 上面的是基础的框架,下面是我们经常需要换的数据
{{ define "content" }}
<p>Default content</p>
{{ end }}

比如另一个文件中使用了上面的框架,其content的内容可以自定义

{{ define "users/index.tmpl" }}
{{ template "base.tmpl" . }}
​
{{ define "content" }}
<h1>{{ .title }}</h1>
<p>Using users/index.tmpl</p>
{{ end }}
{{ end }}

使用模板嵌套可以减少重复代码,统一格式。

自定义渲染

自定义文件后缀

文件后缀不必是tmpl,可以任意,也可以没有

import "html/template"
​
func main() {
    router := gin.Default()
    // 解析模板文件
    html := template.Must(template.ParseFiles("file1", "file2"))
    // 设置 HTML 模板
    router.SetHTMLTemplate(html)
    router.Run(":8080")
}

使用

router.GET("/somepage", func(c *gin.Context) {
    c.HTML(http.StatusOK, "file1", gin.H{
        "title": "Main website",
    })
})

自定义分隔符

r := gin.Default()
    r.Delims("{[{", "}]}")
    r.LoadHTMLGlob("/path/to/templates")

自定义模板功能

import (
    "fmt"
    "html/template"
    "net/http"
    "time"
​
    "github.com/gin-gonic/gin"
)
​
// 格式化时间函数
func formatAsDate(t time.Time) string {
    year, month, day := t.Date()
    return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}
​
func main() {
    router := gin.Default()
    router.Delims("{[{", "}]}")
    router.SetFuncMap(template.FuncMap{
        "formatAsDate": formatAsDate,
    })
    router.LoadHTMLFiles("./testdata/template/raw.tmpl")
​
    router.GET("/raw", func(c *gin.Context) {
        c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
            "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
        })
    })
​
    router.Run(":8080")
}

模板中使用

Date: {[{.now | formatAsDate}]}

1、自定义模板函数

2、注册自定义的模板函数

3、使用自定义函数

路由

路由分组

中间件

TCP与UDP