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)

7
go.mod
View File

@ -2,7 +2,6 @@ module go-udemy-web-1
go 1.21.0
require (
github.com/bmizerany/pat v0.0.0-20210406213842-e4b6760bdd6f // indirect
github.com/go-chi/chi/v5 v5.0.14 // indirect
)
require github.com/go-chi/chi/v5 v5.0.14
require github.com/justinas/nosurf v1.1.1

4
go.sum
View File

@ -1,4 +1,4 @@
github.com/bmizerany/pat v0.0.0-20210406213842-e4b6760bdd6f h1:gOO/tNZMjjvTKZWpY7YnXC72ULNLErRtp94LountVE8=
github.com/bmizerany/pat v0.0.0-20210406213842-e4b6760bdd6f/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c=
github.com/go-chi/chi/v5 v5.0.14 h1:PyEwo2Vudraa0x/Wl6eDRRW2NXBvekgfxyydcM0WGE0=
github.com/go-chi/chi/v5 v5.0.14/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/justinas/nosurf v1.1.1 h1:92Aw44hjSK4MxJeMSyDa7jwuI9GR2J/JCQiaKvXXSlk=
github.com/justinas/nosurf v1.1.1/go.mod h1:ALpWdSbuNGy2lZWtyXdjkYv4edL23oSEgfBT1gPJ5BQ=