Developping our own middleware
This commit is contained in:
parent
e1b990dfd3
commit
9911144aff
29
cmd/web/middleware.go
Normal file
29
cmd/web/middleware.go
Normal 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
|
||||||
|
}
|
@ -13,6 +13,8 @@ func routes(app *config.AppConfig) http.Handler {
|
|||||||
mux := chi.NewMux()
|
mux := chi.NewMux()
|
||||||
|
|
||||||
mux.Use(middleware.Recoverer)
|
mux.Use(middleware.Recoverer)
|
||||||
|
mux.Use(WriteToConsole)
|
||||||
|
mux.Use(NoSurf)
|
||||||
|
|
||||||
mux.Get("/", handlers.Repo.Home)
|
mux.Get("/", handlers.Repo.Home)
|
||||||
mux.Get("/about", handlers.Repo.About)
|
mux.Get("/about", handlers.Repo.About)
|
||||||
|
7
go.mod
7
go.mod
@ -2,7 +2,6 @@ module go-udemy-web-1
|
|||||||
|
|
||||||
go 1.21.0
|
go 1.21.0
|
||||||
|
|
||||||
require (
|
require github.com/go-chi/chi/v5 v5.0.14
|
||||||
github.com/bmizerany/pat v0.0.0-20210406213842-e4b6760bdd6f // indirect
|
|
||||||
github.com/go-chi/chi/v5 v5.0.14 // indirect
|
require github.com/justinas/nosurf v1.1.1
|
||||||
)
|
|
||||||
|
4
go.sum
4
go.sum
@ -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 h1:PyEwo2Vudraa0x/Wl6eDRRW2NXBvekgfxyydcM0WGE0=
|
||||||
github.com/go-chi/chi/v5 v5.0.14/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
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=
|
||||||
|
Loading…
Reference in New Issue
Block a user