快速开始
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//1.创建路由
r := gin.Default()
//2.指定路由规则,执行的函数
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK,"hello world")
})
//3.监听端口,默认是8080
r.Run(":8000")// listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
路由
API参数
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
测试:http://localhost:8000/user/fsl
url参数
r.GET("/welcome", func(c *gin.Context) {
//DefaultQuery没有值的时候取第二个参数
firstname := c.DefaultQuery("firstname", "Guest")
//根据key获取值
lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
表单参数
r.POST("/form_post", func(c *gin.Context) {
message := c.PostForm("message")
nick := c.DefaultPostForm("nick", "anonymous")
c.JSON(200, gin.H{
"status": "posted",
"message": message,
"nick": nick,
})
})
x-www-form-urlencoded
单文件上传
// Set a lower memory limit for multipart forms (default is 32 MiB)
// router.MaxMultipartMemory = 8 << 20 // 8 MiB
r.POST("/upload", func(c *gin.Context) {
// single file
file, _ := c.FormFile("file")
log.Println(file.Filename)
// Upload the file to specific dst.
// c.SaveUploadedFile(file, dst)
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
})
多文件上传
r.POST("/upload", func(c *gin.Context) {
// Multipart form
form, _ := c.MultipartForm()
files := form.File["files"]
for _, file := range files {
log.Println(file.Filename)
// Upload the file to specific dst.
if err:=c.SaveUploadedFile(file,file.Filename);err!=nil{
c.String(http.StatusBadRequest,fmt.Sprintf("uplod err %s",err.Error()))
return
}
}
c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
})
路由组
// Simple group: v1
v1 := r.Group("/v1")
{
v1.POST("/login", loginEndpoint)
v1.POST("/submit", submitEndpoint)
v1.POST("/read", readEndpoint)
}
// Simple group: v2
v2 := r.Group("/v2")
{
v2.POST("/login", loginEndpoint)
v2.POST("/submit", submitEndpoint)
v2.POST("/read", readEndpoint)
}
//3.监听端口,默认是8080
r.Run(":8000") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
func loginEndpoint(c *gin.Context){
fmt.Println("登录")
c.String(http.StatusOK,"登录")
}
func submitEndpoint(c *gin.Context){
c.String(http.StatusOK,"提交")
}
func readEndpoint(c *gin.Context){
c.String(http.StatusOK,"读取")
}