1 回答

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")
}
- 1 回答
- 0 關注
- 116 瀏覽
添加回答
舉報