RESTful
Restful API 是一个广泛使用的软件接口设计模式,其核心思想是通过 HTTP 标签(GET、POST、PUT、DELETE 等)实现对象间的通信。
常见接口类型
- GET: 获取资源信息
- POST: 创建新资源
- PUT: 更新资源状态
- DELETE: 删除资源
标签举例:
API |
Route |
GET |
/api/users |
POST |
/api/users |
PUT |
/api/users |
DELETE |
/api/users |
返回HTML或JSON
1 2 3 4 5 6 7 8
| ginServer.GET("/index", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.html", gin.H{ "title": "dekiru", }) })
|
html页面中所需静态文件应提前加载(Css,Js)
1 2 3 4 5 6
| ginServer.LoadHTMLGlob("templates/*")
ginServer.Static("/static", "./static")
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| ginServer.GET("/json", func(context *gin.Context) {
data := map[string]interface{}{ "name": "mium", "msg": "illusion", }
context.JSON(http.StatusOK, gin.H{ "name": "mium", "msg": "illusion", }) })
|
获取request请求携带的querystring参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| ginServer.GET("/matrix", func(context *gin.Context) {
row, ok := context.GetQuery("row") if !ok { row = "somebody" }
col, ok := context.GetQuery("col") if !ok { col = "somebody" }
context.JSON(http.StatusOK, gin.H{ "row": row, "col": col, }) })
|
1 2 3 4 5 6 7 8 9 10 11
| ginServer.POST("/set", func(context *gin.Context) {
row_ := context.PostForm("matrix_row") col_ := context.PostForm("matrix_col")
context.JSON(http.StatusOK, gin.H{ "row": row_, "col": col_, }) })
|
获取URL路径参数
1 2 3 4 5 6 7 8 9
| ginServer.GET("/:name/:age", func(context *gin.Context) { name := context.Param("name") age := context.Param("age") context.JSON(http.StatusOK, gin.H{ "name": name, "age": age, }) })
|
参数绑定(ShouldBind)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| ginServer.POST("/matrix", func(context *gin.Context) { var x mt.Matrix err := context.ShouldBind(&x) if err != nil { context.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) } else { fmt.Printf("%#v\n", x) context.JSON(http.StatusOK, gin.H{ "satus": "ok", }) } })
|
请求重定向
1 2 3 4 5 6 7 8 9 10 11 12 13
| ginServer.GET("/a", func(context *gin.Context) {
context.Request.URL.Path = "/b" ginServer.HandleContext(context) })
ginServer.GET("/b", func(context *gin.Context) {
context.Redirect(http.StatusMovedPermanently, "https://sagume.cyou") })
|
路由与路由组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
UserGroup := ginServer.Group("/user") { UserGroup.GET("") UserGroup.POST("") UserGroup.PUT("") UserGroup.DELETE("")
}
ginServer.NoRoute(func(context *gin.Context){ context.HTML() })
|