I want the home page to stop being available after a post request. Here is my code. Thanks in advance.
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")
}
My directory structure
-main.go
-pages
-home
-index.html
I am not an expert on gin
but it is similar to echo
so I created a snippet for you to check if it fits your needs.
It looks like it is not possible to detach middleware after attached as discussed here, so my way is to check a global variable for each request to see if the resource is available.
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")
}