Gin
快速入门
- go get -u github.com/gin-gonic/gin
package main
import gin "github.com/gin-gonic/gin"func main() {engine := gin.Default()engine.GET("/", func(c *gin.Context) {c.String(200, "Hello Gin")})engine.Run(":8888")
}
- 热加载
//进入终端执行
go get github.com/pilu/fresh
//然后运行命令
fresh
//如果不成功 get可能不会加入环境变量 使用一次 go install github.com/pilu/fresh
路由基础
package mainimport (gin "github.com/gin-gonic/gin"
)type User struct {Name string `json:"name"`Age int `json:"age"`
}
func main() {engine := gin.Default()engine.LoadHTMLGlob("templates/*") //配置页面模板的位置engine.GET("/", func(c *gin.Context) {c.String(200, "Hello Gin")})engine.GET("/ping", func(c *gin.Context) {//json.Marshal();c.String(200, "pong")})engine.GET("json", func(c *gin.Context) {c.JSON(200, map[string]interface{}{"success": true,"data": map[string]interface{}{"arr": []int{10, 20,},},})})engine.GET("/ch", func(c *gin.Context) {c.JSON(200, gin.H{ //H 就是map[string]interface{}"success": true,})})engine.GET("/struct", func(c *gin.Context) {a := &User{Name: "user",Age: 0,}c.JSON(200, a)//c.XML(200, a)//返回xml//c.HTML(200, "index.html", gin.H{}) //渲染这个模板value := c.Query("aid")c.String(200, "aid:%s", value)})engine.Run(":8888")
}
//前端的使用 {.name}
模板渲染
func main() {router := gin.Default()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",})})router.Run(":8080")
}
//多层目录router.LoadHTMLGlob("templates/**/*")
{{ define "posts/index.html" }} 配置文件<html><h1>{{ .title }}</h1>
</html>
- 一些模板的语法可以看这边https://blog.csdn.net/Tyro_java/article/details/136170586 (官网都没写无语了)
- 公共标题 {{ template “public/index.html”}} 可以引入一个公共的模块
- 配置静态文件
func main() {router := gin.Default()router.Static("/assets", "./assets")router.StaticFS("/more_static", http.Dir("my_file_system"))router.StaticFile("/favicon.ico", "./resources/favicon.ico")// 监听并在 0.0.0.0:8080 上启动服务router.Run(":8080")
}
- 获取参数
func main() {router := gin.Default()router.POST("/post", func(c *gin.Context) {id := c.Query("id")//这个只能获取post的数据page := c.DefaultQuery("page", "0")name := c.PostForm("name")//这个只能获得post的数据message := c.PostForm("message")fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)})router.Run(":8080")
}
- 将参数绑定到结构体
package mainimport ("log""time""github.com/gin-gonic/gin"
)
type Person struct {Name string `form:"name"`Address string `form:"address"`Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
}
func main() {route := gin.Default()route.GET("/testing", startPage)route.Run(":8085")
}
func startPage(c *gin.Context) {var person Person// 如果是 `GET` 请求,只使用 `Form` 绑定引擎(`query`)。// 如果是 `POST` 请求,首先检查 `content-type` 是否为 `JSON` 或 `XML`,然后再使用 `Form`(`form-data`)。// 查看更多:https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L88if c.ShouldBind(&person) == nil {log.Println(person.Name)log.Println(person.Address)log.Println(person.Birthday)}c.String(200, "Success")
}
- 获取原始数据 c.GetRawData()
路由
package mainimport ("github.com/gin-gonic/gin""net/http"
)func main() {r := gin.Default()// 创建一个基础路由组api := r.Group("/api"){api.GET("/users", func(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"message": "获取用户列表"})})api.POST("/users", func(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"message": "创建新用户"})})}r.Run(":8080")
}
中间件
- 外部中间件
- 全局中间件
- 分组中间件
- 中间件和控制器的数据共享
- c.set(“user”,“scc”) c.get(“user”)
- c.copy() 拷贝一个gin.Context
上传文件
func main() {router := gin.Default()// 为 multipart forms 设置较低的内存限制 (默认是 32 MiB)router.MaxMultipartMemory = 8 << 20 // 8 MiBrouter.POST("/upload", func(c *gin.Context) {// 单文件file, _ := c.FormFile("file")log.Println(file.Filename)dst := "./" + file.Filename// 上传文件至指定的完整文件路径c.SaveUploadedFile(file, "./files/" + file.Filename)c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))})router.Run(":8080")
}
- path.join() 拼接路径
cookie
import ("fmt""github.com/gin-gonic/gin"
)func main() {router := gin.Default()router.GET("/cookie", func(c *gin.Context) {cookie, err := c.Cookie("gin_cookie")if err != nil {cookie = "NotSet"c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)}fmt.Printf("Cookie value: %s \n", cookie)})router.Run()
}
session
- 要去下载三方库
Gorm
https://gorm.io/zh_CN/
go-ini
https://ini.unknwon.io/docs/intro/getting_started