猿问

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

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


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


Cats萌萌
浏览 130回答 1
1回答

慕桂英3389331

我不是这方面的专家,gin但它类似于echo所以我创建了一个片段供您检查它是否符合您的需求。看起来在附加后无法分离中间件,如此处所述,所以我的方法是检查每个请求的全局变量以查看资源是否可用。package mainimport (    "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 scopevar noIndex int32func 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")}
随时随地看视频慕课网APP

相关分类

Go
我要回答