func nosurfing(h http.Handler) http.Handler { surfing := nosurf.New(h) surfing.SetFailureHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Println("Failed to validate XSRF Token:", nosurf.Reason(r)) w.WriteHeader(http.StatusBadRequest) })) return surfing }
// WithCsrfHandler is a middleware wrapper providing CSRF validation func WithCsrfHandler(h http.Handler) http.Handler { csrfHandler := nosurf.New(h) csrfHandler.SetFailureHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { rsn := nosurf.Reason(req).Error() log.DebugR(req, "failed csrf validation", log.Data{"reason": rsn}) HTML(w, http.StatusBadRequest, "error", map[string]interface{}{"error": rsn}) })) return csrfHandler }
func failHand(w http.ResponseWriter, r *http.Request) { // will return the reason of the failure fmt.Fprintf(w, "%s\n", nosurf.Reason(r)) }
// csrfFailed is called by nosurf when the csrf token check fails func csrfFailed(w http.ResponseWriter, r *http.Request) { w.WriteHeader(400) fmt.Fprintln(w, nosurf.Reason(r)) // reason of the failure }