Day04 GoWeb开发 | 青训营笔记

38 阅读1分钟

这是我参与「第五届青训营 」笔记创作活动的第4天

Gin

Demo

package main
​
import "github.com/gin-gonic/gin"func main() {
// 创建一个服务
   ginServer := gin.Default()
// 链接数据库的代码
  
// 访问地址,处理我们的请求
  ginServer.GET("/hello", func(context *gin.Context) {
      context.JSON(200, gin.H{"msg": "hello, world!"})
   })
  //服务器端口
   ginServer.Run("localhost:8082")
}

RESTful API

通过不同的请求执行不同的功能

get /user 查询

post /user 提交

Put /user 修改

delete /user 删除

Gin 开发Restful是非常简单的

ginServer.POST("/user", func(context *gin.Context) {
   context.JSON(200, gin.H{"msg": "post,user"})
})
ginServer.PUT("/user")
ginServer.DELETE("/user")

使用postman可以测试得到如下结果

响应一个页面

创建一个index.html页面放在templates文件夹下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>瓦的第一个Go Web页面</title>
</head>
<body>
<h1>你好捏</h1>
</body>
</html>
// 加载静态页面
  ginServer.LoadHTMLGlob("templates/*")
​
  ginServer.GET("/index", func(context *gin.Context) {
    context.HTML(200, "index.html", gin.H{
      "msg": "后台传递的数据",
    })
  })

可以得到如下结果

也可以用ginServer.Static加载资源文件,通过RESTful API实现前后端分离

获取请求中的参数

传统方法:url?userid=xxx&username=yyy

ginServer.GET("/user/info", func(context *gin.Context) {
   userid := context.Query("userid")
   username := context.Query("username")
   context.JSON(http.StatusOK, gin.H{
      "userid":   userid,
      "username": username,
   })
})

RESTful 风格: /user/info/xxx/yyy

ginServer.GET("/user/info/:userid/:username", func(context *gin.Context) {
   userid := context.Param("userid")
   username := context.Param("username")
   context.JSON(http.StatusOK, gin.H{
      "userid":   userid,
      "username": username,
   })
})

前端传数据给后端

go中的json是内置的库

ginServer.POST("/json", func(context *gin.Context) {
   data, _ := context.GetRawData()
   var m map[string]interface{}
   _ = json.Unmarshal(data, &m)
   context.JSON(http.StatusOK, m)
})

路由

路由组

userGroup := ginServer.Group("/user")
{
   userGroup.GET("/add")
   userGroup.POST("login")
   userGroup.POST("logout")
}