亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在發布請求中刪除靜態中間件?

如何在發布請求中刪除靜態中間件?

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 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號