udemy-go-web-1/cmd/web/middleware.go

37 lines
782 B
Go
Raw Normal View History

2024-06-28 11:33:43 +00:00
package main
import (
"fmt"
"net/http"
"github.com/justinas/nosurf"
)
// WriteToConsole writes a log when user hits a page
2024-06-28 11:33:43 +00:00
func WriteToConsole(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Hit the page %s\n", r.URL.String())
next.ServeHTTP(w, r)
})
}
// NoSurf adds CSRF protection to all POST requests
2024-06-28 11:33:43 +00:00
func NoSurf(next http.Handler) http.Handler {
csrfHandler := nosurf.New(next)
csrfHandler.SetBaseCookie(http.Cookie{
HttpOnly: true,
Path: "/",
Secure: app.InProduction,
2024-06-28 11:33:43 +00:00
SameSite: http.SameSiteLaxMode,
})
return csrfHandler
}
// SessionLoad loads and saves the session on every request
func SessionLoad(next http.Handler) http.Handler {
return session.LoadAndSave(next)
}