如何在 post 请求中删除静态中间件?

How do you remove a static middleware on a post request?

我希望主页在 post 请求后停止可用。 这是我的代码。 提前致谢。

package main
import(
    "github.com/gin-contrib/static"
    "github.com/gin-gonic/gin"
)

func main() {
   r := gin.Default()
   r.Use(static.Serve("/", static.LocalFile("./pages/home", true)))
   r.POST("/example", func(c *gin.Context) {
      //here I would like to stop serving the static files on a POST request
   })
   r.Run(":8080")
}

我的目录结构

-main.go
-pages
   -home
      -index.html

我不是 gin 方面的专家,但它与 echo 类似,所以我创建了一个片段供您检查它是否符合您的需求。

附加后中间件似乎无法分离as discussed here,所以我的方法是为每个请求检查一个全局变量以查看资源是否可用。

package main

import (
    "net/http"
    "sync/atomic"

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

// using atomic package instead of using mutexes looks better in this scope
var noIndex int32

func indexMiddleware() gin.HandlerFunc {
    hdl := static.Serve("/", static.LocalFile("./pages/home", true))
    return func(c *gin.Context) {
        if atomic.LoadInt32(&noIndex) == 0 {
            hdl(c)
            // if you have additional middlewares, let them run
            c.Next()
            return
        }
        c.AbortWithStatus(http.StatusBadRequest)
    }
}

func main() {
    r := gin.Default()
    r.Use(indexMiddleware())
    r.POST("/example", func(c *gin.Context) {
        atomic.CompareAndSwapInt32(&noIndex, 0, 1)
        c.String(http.StatusOK, "OK")
    })
    r.Run(":8080")
}