package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// 实例化gin,
// Default 和New的区别:Default使用New实例化,同时使用Logger和Recovery中间件
r := gin.Default()
// 无参数路由
r.GET("/", func(c *gin.Context) {
c.String(200, "Hello, world!")
})
// 有参数路由
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "hi %s", name)
})
// 获取query参数, 匹配users?name=xxx&role=xxx,role可选
r.GET("/users", func(c *gin.Context) {
name := c.Query("name")
role := c.DefaultQuery("role", "teacher")
c.String(http.StatusOK, "%s is a %s", name, role)
})
// 获取post参数
r.POST("/form", func(c *gin.Context) {
username := c.PostForm("username")
password := c.DefaultPostForm("password", "000000") // 可设置默认值
c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
// 字典参数
// curl -g "http://localhost:8080/post?ids[Jack]=001&ids[Tom]=002" -X POST -d 'names[a]=Sam&names[b]=David&names[c]=zzd'
// {"ids":{"Jack":"001","Tom":"002"},"names":{"a":"Sam","b":"David","c":"zzd"}}
r.POST("/post", func(c *gin.Context) {
ids := c.QueryMap("ids")
names := c.PostFormMap("names")
c.JSON(http.StatusOK, gin.H{
"ids": ids,
"names": names,
})
})
// 重定向1,uri将重定向到/ ,即永久重定向
r.GET("/redirect", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "/")
})
// 重定向2,uri是goindex,返回内容为/ uri
r.GET("/goindex", func(c *gin.Context) {
c.Request.URL.Path = "/"
r.HandleContext(c)
})
// group routes 分组路由
defaultHandler := func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"path": c.FullPath(),
})
}
// secondHandler := func(c *gin.Context) {
// c.JSON(http.StatusOK, gin.H{
// "path": c.FullPath(),
// })
// }
// group: v1
v1 := r.Group("/v1")
{
v1.GET("/posts", defaultHandler)
v1.GET("/series", defaultHandler)
}
// group: v2
v2 := r.Group("/v2")
{
v2.GET("/posts", defaultHandler)
v2.GET("/series", defaultHandler)
}
// 上传单文件
r.POST("/upload1", func(c *gin.Context) {
dst := "./tmp/"
file, _ := c.FormFile("file")
c.SaveUploadedFile(file, dst)
c.String(http.StatusOK, "%s uploaded!", file.Filename)
})
// 上传多文件
r.POST("/upload2", func(c *gin.Context) {
// Multipart form
form, _ := c.MultipartForm()
files := form.File["upload[]"]
dst := "./tmp/"
for _, file := range files {
log.Println(file.Filename)
c.SaveUploadedFile(file, dst):
}
c.String(http.StatusOK, "%d files uploaded!", len(files))
})
r.Run() // listen and serve on 0.0.0.0:8080 r.Run(":9999")即运行在 _9999_端口。
}
go gin学习笔记
于 2021-07-01 10:11:43 首次发布