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