Golang | Gin(简洁版)

打印 上一主题 下一主题

主题 971|帖子 971|积分 2913

安装使用



  • Gin 是一个 golang 的微框架,封装比力优雅,API 友好,源代码比力明白。具有快速灵活,容错方便等特点。着实对于 golang 而言,web 框架的依赖远比 python,java 之类的要小。自身的 net/http 足够简单,性能也非常不错。框架更像是一个常用函数或者工具的集合。借助框架开发,不但可以省去许多常用的封装带来的时间,也有助于团队的编码风格和形成规范。
  • Gin 官方文档地点:https://gin-gonic.com/zh-cn.docs
  • 安装 Gin:
  1. go get -u github.com/gin-gonic/gin
复制代码


  • 在 windows 10 系统中,安装 Go1.19 之后的版本,然后打开 go module,在下令行终端中输入:go env -w GO111MODULE=on
  • 修改指定的署理,在下令行终端中输入:go env -w GOPROXY=https:/lgoproxy.io,direct
  1. package main
  2. import "github.com/gin-gonic/gin"
  3. import "github.com/thinkerou/favicon"
  4. func main() {
  5.         // 创建一个服务
  6.         ginServer := gin.Default()
  7.         // 为网页标签导入一个icon
  8.         ginServer.Use(favicon.New("path/to/your/icon"))
  9.         // 连接数据库的代码
  10.        
  11.         // 访问地址,处理请求 Request Response
  12.         ginServer.GET("/hello", func(context *gin.Context) {
  13.                 context.JSON(200, gin.H{"msg": "Hello World!"})
  14.         })
  15.         // gin.H 其实就是一个 map[string]any
  16.        
  17.         // 服务器端口
  18.         ginServer.Run(":8082")
  19. }
复制代码
RESTful API



  • RESTful API(Representational State Transfer API)是一种基于REST架构风格的网络应用编程接口,它通过HTTP协议进行通讯,常用于Web服务的实现。RESTful API遵循一些基本的设计原则,使得服务更加灵活、简单和易于维护。
  • REST的焦点头脑是通过定义资源(Resource)并通过HTTP动词(GET、POST、PUT、DELETE等)对资源进行操作。
  1. // 以前写网站
  2. get /user
  3. post /create_user
  4. post /update_user
  5. post /delete_user
  6. // RESTful API
  7. get /user
  8. post /user
  9. put /user
  10. delete /user
复制代码


  • GET:获取资源,不修改服务器上的数据。
  • POST:创建新的资源,通常用于提交数据。
  • PUT:更新资源,用于替换现有资源。
  • DELETE:删除资源。
  • PATCH:部分更新资源。
  1.         // 访问地址,处理请求 Request Response
  2.         // Gin RestFul 十分简单
  3.         ginServer.GET("/hello", func(context *gin.Context) {
  4.                 context.JSON(200, gin.H{"msg": "Hello World!"})
  5.         })
  6.         ginServer.POST("/user", func(context *gin.Context) {
  7.                 context.JSON(200, gin.H{"msg": "Post user"})
  8.         })
  9.         ginServer.PUT("/user", func(context *gin.Context) {
  10.                 context.JSON(200, gin.H{"msg": "Put user"})
  11.         })
  12.         ginServer.DELETE("/user", func(context *gin.Context) {
  13.                 context.JSON(200, gin.H{"msg": "Delete user"})
  14.         })
复制代码
响应页面

  1.         // 加载静态页面(全局加载)
  2.         ginServer.loadHTMLGlob("templates/*")
  3.        
  4.         // 加载资源文件
  5.         gin.Server.Static("./static","./static")
  6.         // 响应一个页面给前端
  7.         ginServer.GET("/index", func(context *gin.Context) {
  8.                 // context.JSON()  json数据
  9.                 context.HTML(http.StatusOK, "index.html", gin.H{
  10.                         "msg":"This is the data form server."
  11.                 })
  12.                 //  前端用 {{.msg}} 赋值表达式即可取出
  13.         })
复制代码
获取请求参数



  • url?userid=1&username=z3,url传参方式
  1.         ginServer.GET("/user/info", func(context *gin.Context) {
  2.                 userid := context.Query("userid")
  3.                 username := context.Query("username")
  4.                 context.JSON(http.StatusOK, gin.H {
  5.                         "userid":userid,
  6.                         "username":username,
  7.                 })
  8.         })
复制代码


  • url/user/info/1/z3,RestFul风格请求参数
  1.         // :就可以直接取出这个值了
  2.         ginServer.GET("/user/info/:userid/:username", func(context *gin.Context) {
  3.                 userid := context.Param("userid")
  4.                 username := context.Param("username")
  5.                 context.JSON(http.StatusOK, gin.H {
  6.                         "userid":userid,
  7.                         "username":username,
  8.                 })
  9.         })
复制代码
  1.         // 前端给后端传递 json
  2.         ginServer.GET("/json", func(context *gin.Context) {
  3.                 // request.body
  4.                 b, _ := context.GetRawData()
  5.                 var m map[string]interface{}
  6.                 // 返回的是byte切片,包装为json数据
  7.                 _ = json.Unmarshal(b, &m)
  8.                 context.JSON(http.StatusOK, m)
  9.         })
  10.        
  11.         // 处理表单
  12.         ginServer.GET("/user/add", func(context *gin.Context) {
  13.                 username := context.PostForm("username")
  14.                 password := context.PostForm("password")
  15.                
  16.                 // 校验逻辑,略
  17.                
  18.                 context.JSON(http.StatusOK, gin.H {
  19.                         "msg":"ok",
  20.                         "username":username,
  21.                         "password":password,
  22.                 })
  23.         })
复制代码
路由讲解

  1.         ginServer.GET("/json", func(context *gin.Context) {
  2.                 // 重定向
  3.                 context.Redirect(http.StatusMovedPermanently, "https://www.4399.com")
  4.         })
复制代码
  1.         // 404 NoRoute
  2.         ginServer.NoRoute(func(context *gin.Context) {
  3.                 context.Redirect(http.StatusNotFound, "404.html", nil)
  4.         })
复制代码
  1.         // 路由组
  2.         userGroup := ginServer.Group("/user"){
  3.                 userGroup.POST("/add", func)
  4.                 userGroup.POST("/login", func)
  5.                 userGroup.POST("/logout", func)
  6.         }
  7.         orderGroup := ginServer.Group("/order"){
  8.                 orderGroup.POST("/add", func)
  9.                 orderGroup.DELETE("/delete", func)
  10.         }
复制代码
中间件

  1.         // go中间件可以进行预处理,登录授权、验证、分页等
  2.         // 自定义go中间件 拦截器
  3.         func myHandler() (gin.HandlerFunc) {
  4.                 return func(context *gin.Context) {
  5.                         // 通过自定义的中间件,设置的值在后续处理只要调用了这个中间件都可以拿到这里的值
  6.                         context.Set("usersession", "userid-1")
  7.                         if condition {
  8.                                 context.Next() // 放行
  9.                         } else {
  10.                                 context.Abort() // 阻止
  11.                         }
  12.                 }
  13.         }
  14.         ginServer.GET("/user/info", myHandler(), func(context *gin.Context) {
  15.                 // 取出中间件中的值
  16.                 usersession := context.MustGet("userSession").(string)
  17.                 log.Println("userSession", usersession)
  18.                 userid := context.Query("userid")
  19.                 username := context.Query("username")
  20.                 context.JSON(http.StatusOK, gin.H {
  21.                         "userid":userid,
  22.                         "username":username,
  23.                 })
  24.         })
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

涛声依旧在

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表