Developping our own middleware

This commit is contained in:
Muyao CHEN
2024-06-28 13:33:43 +02:00
parent e1b990dfd3
commit 9911144aff
4 changed files with 36 additions and 6 deletions

29
cmd/web/middleware.go Normal file
View File

@ -0,0 +1,29 @@
package main
import (
"fmt"
"net/http"
"github.com/justinas/nosurf"
)
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)
})
}
func NoSurf(next http.Handler) http.Handler {
csrfHandler := nosurf.New(next)
csrfHandler.SetBaseCookie(http.Cookie{
HttpOnly: true,
Path: "/",
Secure: false,
SameSite: http.SameSiteLaxMode,
})
return csrfHandler
}

View File

@ -13,6 +13,8 @@ func routes(app *config.AppConfig) http.Handler {
mux := chi.NewMux()
mux.Use(middleware.Recoverer)
mux.Use(WriteToConsole)
mux.Use(NoSurf)
mux.Get("/", handlers.Repo.Home)
mux.Get("/about", handlers.Repo.About)