2、快速入门
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run()
}
3、路由组
userGroup := r.Group("/user")
{
userGroup.GET("/", func(context *gin.Context) {})
userGroup.POST("/", func(context *gin.Context) {})
}
4、请求响应
4.1 返回Json
r.GET("/json1", func(context *gin.Context) {
data := gin.H{"name": "ckz",
"age": 24}
context.JSON(http.StatusOK, data)
})
student := Student{Name: "Clark", Sex: "male", Age: 24}
r.GET("/json2", func(context *gin.Context) {
context.JSON(http.StatusOK, student)
})
4.2 参数绑定
r.GET("/query", func(context *gin.Context) {
query := context.Query("name")
context.JSON(http.StatusOK, gin.H{"name": query})
})
r.POST("/form", func(context *gin.Context) {
username := context.PostForm("username")
password := context.PostForm("password")
context.JSON(http.StatusOK, gin.H{"username": username, "password": password})
})
r.GET("/user/:username", func(context *gin.Context) {
username := context.Param("username")
context.JSON(http.StatusOK, gin.H{"username": username})
})
r.GET("/bind", func(context *gin.Context) {
var user User
err := context.ShouldBind(&user)
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
})
5、文件上传
r.POST("/upload", func(context *gin.Context) {
file, err := context.FormFile("File")
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
dst := "./" + file.Filename
err = context.SaveUploadedFile(file, dst)
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
})
r.POST("/uploads", func(context *gin.Context) {
form, err := context.MultipartForm()
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
files := form.File["file"]
for _, file := range files {
dst := "./" + file.Filename
err = context.SaveUploadedFile(file, dst)
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
}
context.JSON(http.StatusOK, gin.H{"success": "success"})
# })