Go Gin

105 阅读1分钟

1、官方参考文档

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() // 监听并在 0.0.0.0:8080 上启动服务
}

3、路由组

	// Group
	userGroup := r.Group("/user")
	{
		userGroup.GET("/", func(context *gin.Context) {})

		userGroup.POST("/", func(context *gin.Context) {})
	}

4、请求响应

4.1 返回Json

	// 方法一 map
	r.GET("/json1", func(context *gin.Context) {
		data := gin.H{"name": "ckz",
			"age": 24}
		context.JSON(http.StatusOK, data)
	})

	// 方法二 struct
	student := Student{Name: "Clark", Sex: "male", Age: 24}
	r.GET("/json2", func(context *gin.Context) {
		context.JSON(http.StatusOK, student)
	})

4.2 参数绑定

	// queryString
	r.GET("/query", func(context *gin.Context) {
		query := context.Query("name")
		// defaultQuery := context.DefaultQuery("name", "ckz")
		// name, ok := context.GetQuery("name") //取不到ok 为false
		context.JSON(http.StatusOK, gin.H{"name": query})
	})

	// formData
	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})
	})

	// path
	r.GET("/user/:username", func(context *gin.Context) {
		username := context.Param("username")
		context.JSON(http.StatusOK, gin.H{"username": username})
	})

	// bind get post 都能绑定
	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、文件上传

	// upload 上传单个文件
	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
		}
	})

	// upload 上传多个文件
	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"})
# })