路由
- 一. 常规路由
- 二. 动态路由
- 三. 带参数的路由
- 3.1 GET
- 3.2 POST
- 3.3 绑定
- 四. 简单的路由组
- 五. 文件分组
一. 常规路由
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func index(ctx *gin.Context) {
ctx.String(http.StatusOK, "Hello Gin")
}
func main() {
r := gin.Default()
r.GET("/", index)
r.Run(":80")
}
此时访问http://localhost/
即可得到:
二. 动态路由
func uid(ctx *gin.Context) {
userid := ctx.Param("uid")
ctx.String(http.StatusOK, "User ID is: "+userid)
}
r.GET("/:uid", uid)
- 缺点是不能像
Django
那样指定参数类型,这个
三. 带参数的路由
3.1 GET
对于GET
方式的参数,咱们可以使用Query
系列的操作
func (c *Context) Query(key string) (value string)
func (c *Context) QueryArray(key string) (values []string)
func (c *Context) QueryMap(key string) (dicts map[string]string)
func (c *Context) DefaultQuery(key, defaultValue string) string
例子:
r.GET("/AddInt", func(ctx *gin.Context) {
num := ctx.Query("num")
opt := ctx.DefaultQuery("option", "GET")
ctx.String(http.StatusOK, "num is %s option is %s", num, opt)
})
3.2 POST
POST
同理
func (c *Context) DefaultPostForm(key, defaultValue string) string
func (c *Context) PostForm(key string) (value string)
func (c *Context) PostFormArray(key string) (values []string)
func (c *Context) PostFormMap(key string) (dicts map[string]string)
3.3 绑定
通过绑定,可以将各种数据绑定到各种对象上
func (c *Context) ShouldBind(obj any) error
func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error)
func (c *Context) ShouldBindHeader(obj any) error
func (c *Context) ShouldBindJSON(obj any) error
func (c *Context) ShouldBindQuery(obj any) error
func (c *Context) ShouldBindTOML(obj any) error
func (c *Context) ShouldBindUri(obj any) error
func (c *Context) ShouldBindWith(obj any, b binding.Binding) error
func (c *Context) ShouldBindXML(obj any) error
func (c *Context) ShouldBindYAML(obj any) error
例如:
type AddType struct {
Num1 string
Num2 string
}
func main() {
r := gin.Default()
r.GET("/AddInt", func(ctx *gin.Context) {
var num AddType
if err := ctx.ShouldBind(&num); err == nil {
ctx.String(http.StatusOK, "num1 is %s num2 is %s", num.Num1, num.Num2)
} else {
ctx.String(http.StatusBadRequest, "Error")
}
})
r.Run(":80")
}
但是空成员也不会报错:
四. 简单的路由组
v1 := r.Group("/v1")
{
v1.GET("/login", func(ctx *gin.Context) {
ctx.String(http.StatusOK, "Success")
})
}
v2 := r.Group("/v2")
{
v2.POST("/login", func(ctx *gin.Context) {
ctx.String(http.StatusOK, "Success")
})
}
五. 文件分组
新建文件夹routers
,并且在该文件夹下将路由分为两个:v1.go
和v2.go
package routers
import (
"net/http"
"github.com/gin-gonic/gin"
)
func V1RoutesInit(router *gin.Engine) {
v1Router := router.Group("/v1")
{
v1Router.GET("/user", func(c *gin.Context) {
c.String(http.StatusOK, "v1查询")
})
}
}
package routers
import (
"net/http"
"github.com/gin-gonic/gin"
)
func V2RoutesInit(router *gin.Engine) {
v2Router := router.Group("/v2")
{
v2Router.GET("/user", func(c *gin.Context) {
c.String(http.StatusOK, "v2查询")
})
}
}
然后在main.go
里:imort moudel/package
,比如"kanna-web/routers"
然后即可调用:
routers.V1RoutesInit(r)
routers.V2RoutesInit(r)