Gin 框架学习笔记

Gin

示例

package main

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "time"

    "github.com/didip/tollbooth"
    "github.com/didip/tollbooth/limiter"
    "github.com/ffhelicopter/tmm/api"
    "github.com/ffhelicopter/tmm/handler"

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

// 定义全局的CORS中间件
func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
        c.Next()
    }
}

func LimitHandler(lmt *limiter.Limiter) gin.HandlerFunc {
    return func(c *gin.Context) {
        httpError := tollbooth.LimitByRequest(lmt, c.Writer, c.Request)
        if httpError != nil {
            c.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message))
            c.Abort()
        } else {
            c.Next()
        }
    }
}

func main() {
    gin.SetMode(gin.ReleaseMode)
    router := gin.Default()

    // 静态资源加载,本例为css,js以及资源图片
    router.StaticFS("/public", http.Dir("D:/goproject/src/github.com/ffhelicopter/tmm/website/static"))
    router.StaticFile("/favicon.ico", "./resources/favicon.ico")

    // 导入所有模板,多级目录结构需要这样写
    router.LoadHTMLGlob("website/tpl/*/*")
    // 也可以根据handler,实时导入模板。

    // website分组
    v := router.Group("/")
    {
        v.GET("/index.html", handler.IndexHandler)
        v.GET("/add.html", handler.AddHandler)
        v.POST("/postme.html", handler.PostmeHandler)
    }

    // 中间件 golang的net/http设计的一大特点就是特别容易构建中间件。
    // gin也提供了类似的中间件。需要注意的是中间件只对注册过的路由函数起作用。
    // 对于分组路由,嵌套使用中间件,可以限定中间件的作用范围。
    // 大致分为全局中间件,单个路由中间件和群组中间件。

    // 使用全局CORS中间件。
    // router.Use(Cors())
    // 即使是全局中间件,在use前的代码不受影响
    // 也可在handler中局部使用,见api.GetUser

    //rate-limit 中间件
    lmt := tollbooth.NewLimiter(1, nil)
    lmt.SetMessage("服务繁忙,请稍后再试...")

    // API分组(RESTFULL)以及版本控制
    v1 := router.Group("/v1")
    {
        // 下面是群组中间的用法
        // v1.Use(Cors())

        // 单个中间件的用法
        // v1.GET("/user/:id/*action",Cors(), api.GetUser)

        // rate-limit
        v1.GET("/user/:id/*action", LimitHandler(lmt), api.GetUser)

        //v1.GET("/user/:id/*action", Cors(), api.GetUser)
        // AJAX OPTIONS ,下面是有关OPTIONS用法的示例
        // v1.OPTIONS("/users", OptionsUser)      // POST
        // v1.OPTIONS("/users/:id", OptionsUser)  // PUT, DELETE
    }

    srv := &http.Server{
        Addr:         ":80",
        Handler:      router,
        ReadTimeout:  30 * time.Second,
        WriteTimeout: 30 * time.Second,
    }

    go func() {
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("listen: %s\n", err)
        }
    }()

    // 优雅Shutdown(或重启)服务
    // 5秒后优雅Shutdown服务
    quit := make(chan os.Signal)
    signal.Notify(quit, os.Interrupt) //syscall.SIGKILL
    <-quit
    log.Println("Shutdown Server ...")

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    if err := srv.Shutdown(ctx); err != nil {
        log.Fatal("Server Shutdown:", err)
    }
    select {
    case <-ctx.Done():
    }
    log.Println("Server exiting")
}

基本运行方法

实例化一个gin的server对象

生成一个 Engine,这是 gin 的核心,默认带有 Logger 和 Recovery 两个中间件。

router := gin.Default()

加载静态资源

func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes
func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes
// 静态资源加载,本例为css,js以及资源图片
router.StaticFS("/public", http.Dir("D:/goproject/src/github.com/ffhelicopter/tmm/website/static"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")

导入模板

//导入所有模板,多级目录结构需要这样写
router.LoadHTMLGlob("website/tpl/*/*")

路由分组

// website分组
v := router.Group("/")
{
    v.GET("/index.html", handler.IndexHandler)
    v.GET("/user/:name", func(c *gin.Context) {
		// 获取请求path中的参数
		name := c.Param("name")
		for _, user := range users {
			if user.Username == name {
				c.JSON(http.StatusOK, user)
				return
			}
		}
		c.JSON(http.StatusOK, fmt.Errorf("not found user [%s]", name))
	})
    v.GET("/add.html", handler.AddHandler)
    v.POST("/postme.html", handler.PostmeHandler)
}

启动服务器

router.Run(":80")

中间件

中间件列表

// 全局中间件注册
route.Use(costTimeMiddleware())
// 局部中间件注册
route.GET("/hello", costTimeMiddleware(), func(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "hello world!",
	})
})

posted @   嘿,抬头!  阅读(94)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示