Gin笔记 | 青训营

79 阅读1分钟

小白自用

第一个Gin程序

package main

import "github.com/gin-gonic/gin"

func main() {
	r := gin.Default() //生成一个实例
        
 // r.Get("/",……)声明一个路由 什么样的url能触发函数
	r.GET("/", func(c *gin.Context) {
		c.String(200, "Hello, Geektutu")
	})
	r.Run() // listen and serve on 0.0.0.0:8080
}

动态的路由,如 /user/:name,通过调用不同的url来传入不同的name。/user/:name/*role* 代表可选。 r := gin.Default() //生成一个实例;r.Get("/",……)声明一个路由 什么样的url能触发函数。

$ curl http://localhost:9999/user/geektutu

// 匹配 /user/geektutu
r.GET("/user/:name", func(c *gin.Context) {
	name := c.Param("name")
	c.String(http.StatusOK, "Hello %s", name)

获取Query参数

$ curl "http://localhost:9999/users?name=Tom&role=student"

// 匹配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参数

$ curl http://localhost:9999/form -X POST -d 'username=geektutu&password=1234'

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,
	})

Query和POST混合参数

$ curl "http://localhost:9999/posts?id=9876&page=7" -X POST -d 'username=geektutu&password=1234'

r.POST("/posts", func(c *gin.Context) {
	id := c.Query("id")
	page := c.DefaultQuery("page", "0")
	username := c.PostForm("username")
	password := c.DefaultPostForm("username", "000000") // 可设置默认值

	c.JSON(http.StatusOK, gin.H{
		"id":       id,
		"page":     page,
		"username": username,
		"password": password,
	})
})

Map参数(字典参数)

$ curl -g "http://localhost:9999/post?ids[Jack]=001&ids[Tom]=002" -X POST -d 'names[a]=Sam&names[b]=David'

结果: {"ids":{"Jack":"001","Tom":"002"},"names":{"a":"Sam","b":"David"}}

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,
	})
})