为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
Cats萌萌 2022-05-10 17:12:00
我希望主页在发布请求后停止可用。这是我的代码。提前致谢。package mainimport(    "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
查看完整描述

1 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

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


看起来在附加后无法分离中间件,如此处所述,所以我的方法是检查每个请求的全局变量以查看资源是否可用。


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

}


查看完整回答
反对 回复 2022-05-10
  • 1 回答
  • 0 关注
  • 129 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号