gin 路由
★基本路由
-
gin 框架中采用的路由库是基于httprouter做的
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { //1.创建路由 r := gin.Default() //2.绑定路由规则,执行的函数 r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "hello word") }) r.PUT("/xxxpost") //3.监听端口,默认是8080 r.Run(":8080") }
★Restful风格API
-
gin支持Restful风格的API
-
即Representational State Transfer的缩写。直接翻译的意思是"表现层状态转化",是一种互联网应用程序的API设计理念:URL定位资源,用HTTP描述操作
1.获取文章 /blog/getXxx Get blog/Xxx
2.添加 /blog/addXxx POST blog/Xxx
3.修改 /blog/updateXxx PUT blog/Xxx
4.删除 /blog/delXxxx DELETE blog/Xxx
★API参数
-
可以通过Context的Param方法来获取API参数
-
localhost:8000/xxx/zhangsan
package main import ( "net/http" "strings" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/user/:name/*action", func(c *gin.Context) { name := c.Param("name") action := c.Param("action") action = strings.Trim(action, "/") c.String(http.StatusOK, name+" is "+action) }) //默认监听8080端口 r.Run(":8080") }