利用Gin实现简单的用户管理(1)| 豆包MarsCode AI刷题

102 阅读3分钟

利用Gin实现简单的用户管理(1)

用到的知识

  • Gin框架
  • cookie

Gin

Gin是一个高性能的Go Web框架,常用于快速构建 RESTful API 和 Web 应用。以下是Gin框架的基础用法。

1. 安装Gin

在你的项目中使用go mod,并通过以下命令安装Gin:

go get -u github.com/gin-gonic/gin

或者先引入再tidy以下都是可以的:

先引入:

import "github.com/gin-gonic/gin"

tidy:

go mod tidy

2. 快速入门

简单示例
package main
import (
    "github.com/gin-gonic/gin"
)
func main(){
   router := gin.Default()//创建路由对象,并加载默认中间件(日志和恢复)
    
    // 定义一个简单的 GET 路由
   router.GET("/hello",func(context *gin.Context) {
       context.String(200,"hello world!!!")
   })
    //启动服务器,监听端口
   router.Run() //默认监听: 8080
}

在这里200是HTRP状态码。也可以用http.StatusOK来表示200,除此之外还有:

  • http.StatusNotFound(404):表示请求的资源未找到。
  • http.StatusInternalServerError(500):表示服务器内部错误。

此时在浏览器里访问127.0.0.1:8080/hello会出现hello world!!!这个字样。

其中func(context *gin.Context)函数也可以在外部声明后在这里使用:

package main
import (
    "github.com/gin-gonic/gin"
)
func main(){
   router := gin.Default()
   router.GET("/hello",hello) 
   router.Run() 
}
func hello (context *gin.Context) {
       context.String(200,"hello world!!!")
}

3. 路由

Gin提供了强大的路由功能,包括静态路由、动态路由和分组路由。在这里我们先只展示静态路由。

静态路由
router.GET("/hello",func(context *gin.Context) {
       context.String(200,"hello world!!!")
   })

4. 中间体

中间件是 Gin 的重要功能,用于处理请求前或请求后添加额外的逻辑。

使用默认中间体

默认中间件包含日志和崩溃恢复功能:

router := gin.Default() // 默认加载 Logger 和 Recovery 中间件
自定义中间体
func Logger() gin.HandlerFunc {
    return func(context *gin.Context) {
        // 在请求处理之前执行
        startTime := time.Now()
        
        // 处理请求
        context.Next()
        
        // 在请求处理之后执行
        latency := time.Since(startTime)
        status := context.Writer.Status()
        log.Printf("Status: %d | Latency: %v", status, latency)
    }
}
​
router.Use(Logger()) // 全局注册中间件

5.静态文件和模板

静态文件

Gin可以轻松加载静态文件:

gorouter.Static("/hello","./hello") // 映射 /hello 路径到 ./hello 文件夹

访问 /hello/hello.txt 会自动加载 ./hello/hello.txt 文件。

HTML模板渲染
加载模板文件

将 HTML 文件放在templates文件夹中,比如templates/index.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
</head>
<body>
    <h3>欢迎来到我的用户管理系统</h3>
    <form action="/login" method="GET">
        <input type="submit" value="登录">
    </form>
    <form action="/register" method="GET">
        <input type="submit" value="注册">
    </form>
    </form>
        <h4>秘密通道</h4>
    <form action="/mimi" method="GET">
        <input type="submit" value="秘密通道">
    </form>
</body>
</html>
渲染模板
router.LoadHTMLGlob("./templates/*") // * 是加载文件夹里的所有文件
router.GET("/",index)
​
​
​
​
func index (context *gin.Context){
    context.HTML(200,"index.html",nil)
}

6. 错误处理

Gin提供了简单的错误处理机制:

router.GET("/error", func(context *gin.Context) {
    context.AbortWithStatusJSON(http.StatusNotFound, gin.H{
        "error": "Resource not found",
    })
})
gin.H
  1. 定义: gin.H 是 Gin 框架中用于构建 JSON 响应的一个类型。它实际上是一个 map[string]interface{} 的别名,允许我们以键值对的形式构建 JSON 数据。
  2. 用法: 在 Gin 中,我们可以使用 gin.H 来快速创建 JSON 响应。例如,在处理 GET 请求时,可以通过 context.JSON() 方法将数据以 JSON 格式返回给客户端。使用 gin.H 可以使代码更加简洁和易读。
context.JSON(200,gin.H{
    "usename": "xaiowang",
    "age" : 18,
})

小结

Gin 是一个功能强大且易于使用的 Go Web 框架,适合用来开发快速响应的 API 和 Web 应用。通过其简单的 API 和丰富的中间件支持,Gin 能够满足绝大部分 Web 开发的需求。