Imooc gin入门:请求路由
2-2/5 gin基础:请求路由 - 章节介绍
请求路由
多种请求类型
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/get", func(c *gin.Context) {
c.String(200, "get")
})
r.POST("/post", func(c *gin.Context) {
c.String(200, "post")
})
r.Handle("DELETE", "/del", func(c *gin.Context) {
c.String(200, "delete")
})
// 对应8路路由
r.Any("/any", func(c *gin.Context) {
c.String(200, "any")
})
r.Run()
}
curl -X GET "http://localhost:8080/get"
curl -X POST "http://localhost:8080/post"
curl -X DELETE "http://localhost:8080/del"
静态文件夹
r := gin.Default()
r.Static("/assets", "./assets")
r.StaticFS("/static", http.Dir("static"))
r.StaticFile("/favicon.ico", "./favicon.ico")
r.Run()
# 注意这里,如果直接用 GoLand 运行,会找不到静态文件
cd router-statics
go build -o router-statics && ./router-statics
# 这里的 localhost 会失败
❯ curl "http://127.0.0.1:8080/assets/1.html"
参数作为URL
r := gin.Default()
r.GET("/:name/:id", func(c *gin.Context) {
c.JSON(200, gin.H{
"name": c.Param("name"),
"id": c.Param("id"),
})
})
r.Run()
❯ curl "http://127.0.0.1:8080/aric/11"
{"id":"11","name":"aric"}
泛绑定
r := gin.Default()
r.GET("/user/*action", func(c *gin.Context) {
c.String(200, "hello * world")
})
r.Run()
❯ curl "http://127.0.0.1:8080/user/11"
hello * world
参考