go - 如何在发布请求中删除静态中间件?

标签 go go-gin

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

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")
}

关于go - 如何在发布请求中删除静态中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60016406/

相关文章:

go - 使用 goroutines 时将函数调用包装到闭包中

rest - 如何使用 Gin-Gonic 在 Go 中读取 snake case JSON 请求体

date - gin/golang gin-gonic 不解析时间。unix json 的正确时间?

go - 运行前如何通过gin合并多个路由器

Golang 相当于 Python 的 struct.pack/struct.unpack

go - 如何使用 gomail 设置发送为电子邮件地址

go - 'go'工具安装可执行文件后如何访问资源文件?

sql-server - 戈兰 : "Err TLS Handshake failed: tls: server selected unsupported protocol version 301" when trying to connect to sql server (diferent host)

Golang Gin : serving JSON and static files in the same app

go - 解码时如何跳过元素?