This Gin middleware generates a nonce for each request.
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"go.eigsys.de/gin-nonce"
)
func main() {
router := gin.Default()
handler := nonce.New()
router.Use(handler.Middleware())
router.GET("/", func(ginCtx *gin.Context) {
currentNonce, _ := handler.GetNonce(ginCtx)
ginCtx.Header("Content-Security-Policy", fmt.Sprintf("style-src 'nonce-%s';", currentNonce))
ginCtx.String(http.StatusOK, "Hello, Gopher!")
})
_ = router.Run()
}
See Go reference.