RESTful

Restful API 是一个广泛使用的软件接口设计模式,其核心思想是通过 HTTP 标签(GET、POST、PUT、DELETE 等)实现对象间的通信。

常见接口类型

  1. GET: 获取资源信息
  2. POST: 创建新资源
  3. PUT: 更新资源状态
  4. 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
// *返回HTML
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/*")

// *静态文件加载{ css . js }
ginServer.Static("/static", "./static")

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// *返回JSON
ginServer.GET("/json", func(context *gin.Context) {

data := map[string]interface{}{
"name": "mium",
"msg": "illusion",
}

//JSON序列化->反射机制{无法访问小写field}->用`tag`自定义`json`
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
// *获取request携带querystring参数{ Query / DefaultQuery / GetQuery}
ginServer.GET("/matrix", func(context *gin.Context) {

// name := context.Query("query")
// name = context.DefaultQuery("query", "Somebody")
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,
})
})

获取request请求携带的form参数

1
2
3
4
5
6
7
8
9
10
11
// *获取request携带form参数{ Postform / DefaultPostform / GetPostform}
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
//	*获取URL路径参数{Param :注意匹配时的路由冲突}
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
//	*参数绑定{ShouldBind(指针)}
ginServer.POST("/matrix", func(context *gin.Context) {
var x mt.Matrix
err := context.ShouldBind(&x)
//利用反射->获取结构体字段;利用tag->选定表单或JSON
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
//	*路由与路由组

/*
请求方式 :访问路径 ————> 对应函数

post : "/index" ————> func(){}

*/

// *路由组
UserGroup := ginServer.Group("/user")
{
UserGroup.GET("")
UserGroup.POST("")
UserGroup.PUT("")
UserGroup.DELETE("")

}

// *自定义404
ginServer.NoRoute(func(context *gin.Context){
context.HTML()
})