这是我参与「第三届青训营 -后端场」笔记创作活动的的第5篇笔记
获取Get参数
package main
import "github.com/gin-gonic/gin"
func main() {
router := gin.Default()
// /hello?key=1 获取get请求的参数的三种方式
router.GET("/hello", func(context *gin.Context) {
key := context.Query("key")
// 获取不到就设置为默认值
key2 := context.DefaultQuery("key","defaultValue")
// ok 为是否获取到
key3, ok := context.GetQuery("ket")
if !ok {
key3 = "defaultValue"
}
context.JSON(200, gin.H{
"key" : key,
"key2": key2,
"ke3": key3,
})
})
// 启动服务绑定端口
router.Run(":9090")
}
获取Post请求参数
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// 返回默认的路由引擎
router := gin.Default()
// 获取Post表单数据
router.POST("/hello", func(context *gin.Context) {
key := context.PostForm("key")
key2 := context.DefaultPostForm("key", "defaultValue")
context.JSON(http.StatusOK, gin.H{
"key": key,
"key2": key2,
})
})
// 启动服务绑定端口
router.Run(":9090")
}
获取路径中的请求值
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// 返回默认的路由引擎
router := gin.Default()
// 获取路径中的参数值 /hello/value1/value2
router.GET("/hello/:value1/:value2", func(context *gin.Context) {
value1 := context.Param("value1")
value2 := context.Param("value2")
context.JSON(http.StatusOK, gin.H{
"key1": value1,
"key2": value2,
})
})
// 启动服务绑定端口
router.Run(":9090")
}
将参数绑定到结构体
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
// 映射 将 form表单中的值映射过来
type User struct {
Username string `form:"username"`
Password string `form:"password"`
}
func main() {
// 返回默认的路由引擎
router := gin.Default()
// 将参数绑定到结构体
router.GET("/hello", func(context *gin.Context) {
var u User
err := context.ShouldBind(&u)
if err != nil {
fmt.Println(err)
}
fmt.Println(u)
})
// 启动服务绑定端口
router.Run(":9090")
}