From 9911144aff5568c4f4576bbdc7f8c2b95f23e227 Mon Sep 17 00:00:00 2001 From: Muyao CHEN Date: Fri, 28 Jun 2024 13:33:43 +0200 Subject: [PATCH] Developping our own middleware --- cmd/web/middleware.go | 29 +++++++++++++++++++++++++++++ cmd/web/routes.go | 2 ++ go.mod | 7 +++---- go.sum | 4 ++-- 4 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 cmd/web/middleware.go diff --git a/cmd/web/middleware.go b/cmd/web/middleware.go new file mode 100644 index 0000000..e907914 --- /dev/null +++ b/cmd/web/middleware.go @@ -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 +} diff --git a/cmd/web/routes.go b/cmd/web/routes.go index 4302753..8102ef7 100644 --- a/cmd/web/routes.go +++ b/cmd/web/routes.go @@ -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) diff --git a/go.mod b/go.mod index 7285979..3a3ea64 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index d1652b0..3a7dd97 100644 --- a/go.sum +++ b/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/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=