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")
}
func uid(ctx *gin.Context) {
userid := ctx.Param("uid")
ctx.String(http.StatusOK, "User ID is: "+userid)
}
r.GET("/:uid", uid)
Django
那样指定参数类型,这个对于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)
})
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)
通过绑定,可以将各种数据绑定到各种对象上
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)