gin框架

gin框架

配置代理

windows系统
# 设置 goproxy.io 代理。
go env -w GOPROXY="https://goproxy.io"
# 设置 GO111MOUDLE。
go env -w GO111MODULE="on"

linux系统
# 设置 goproxy.io 代理。
export GOPROXY=https://goproxy.io
# 设置 GO111MOUDLE。
export GO111MODULE=on

安装

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

使用

package main

import "github.com/gin-gonic/gin"

type UserInfo struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Id       int    `json:"id"`
	Phone    int    `json:"phone"`
}

func main() {
	r := gin.Default()
	r.LoadHTMLGlob("templates/*")  //加载静态页面目录
	//响应一个Json数据,200为状态码
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "Hello Word",
		}) //响应一个Json数据
	})
	//响应一个字符串
	r.GET("/news", func(ctx *gin.Context) {
		ctx.String(200, "news") //响应一个字符串
	})
	//响应一个json结构体
	r.GET("/json2", func(ctx *gin.Context) {
		a := UserInfo{
			Username: "zs",
			Password: "123456",
			Id:       1,
			Phone:    13333333333,
		}
		ctx.JSON(200, a) //响应一个结构体
	})

	//响应Jsonp  ?callback=data
	r.GET("/jsonp", func(ctx *gin.Context) {
		ctx.JSONP(200, gin.H{
			"message": "ok",
		})
	})
	r.GET("/index", func(ctx *gin.Context) {
		ctx.HTML(200, "index.html", gin.H{
			"message": "hahaha",
		})
    }) //前段使用传参为{{.message}}
	r.GET("/xml", func(ctx *gin.Context) {
		ctx.XML(200, gin.H{
			"message": "你好",
			"status":  true,
		})
	})
	//两种启动方式都可以
	r.Run(":9000")
    http.ListenAndServe(":9000", r)
}

gin 中没有热加载工具,这个时候我们要实现热加载就可以借助第三方的工具。

go get github.com/pilu/fresh
fresh

模板渲染

router := gin.Default()
router.LoadHTMLGlob("templates/*")

如模板处于多个目录

router.LoadHTMLGlob("templates/**/*")  多层目录用/**表示
templates
----目录1
	---index.html
----目录2
	----index.html
对应的index文件首尾需加以下关键字
{{ define  "目录1/index.html"}}
{{ end }}

模板基本语法

{{.变量名}}  用于输出后端传给模板的变量
{{$c :=.变量}} 自定义变量c接收后端传过来的值
比较函数  eq  ne  lt le gt ge 与shell类似
条件判断语法
{{if gt .score 90}}
优秀
{{else if  gt .score 80}}
良好
{{else}}
差
{{end}}
遍历range
{{range $key,$value :=.变量}}
	{{¥value}}
{{end}}

with 遍历结构体
{{with .user}}
	{{.name}}
	{{.age}}
{{end}}

自定义模板函数

后端
func formatAsDate(t time.Time) string {
	year, month, day := t.Date()
	return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}

//注册全局模板函数 注意顺序,注册模板函数需要在加载模板上面
router.SetFuncMap(template.FuncMap{ 
	"formatDate": formatAsDate, 
})

前端
{{.now | formatDate}}
或者
{{formatDate .now }}

模板嵌套

新建 templates/deafult/page_header.html 写入如下内容
{{ define "default/page_header.html" }}
<h1>这是一个头部</h1>
{{end}}

外部引入
{{template "default/page_header.html" .}} //引入的时候注意最后的点(.)

静态文件

当我们渲染的 HTML 文件中引用了静态文件时,我们需要配置静态 web 服务
router := gin.Default()
router.Static("/static", "./static") 前面的/static 表示路由 后面的./static 表示路径

前端
<link rel="stylesheet" href="/static/css/base.css" />

gin框架
http://www.jcwit.com/article/505/
作者
Carlos
发布于
2024年3月26日
许可协议