From 5224fcdbba087d6e388568ecf5fddf23e3e228cb Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Wed, 7 Aug 2024 17:00:46 +0200 Subject: Allow the user to change their theme --- main.go | 30 +++++++++++ templates/navbar.templ | 2 +- templates/navbar_templ.go | 4 +- templates/root_templ.go | 123 +++++++++++++++++++++++++--------------------- 4 files changed, 101 insertions(+), 58 deletions(-) diff --git a/main.go b/main.go index 464f93a..22b23ea 100644 --- a/main.go +++ b/main.go @@ -38,6 +38,7 @@ func main() { )(http.HandlerFunc(finalHandler))) mux.Handle("POST /language", http.HandlerFunc(setUserLanguage)) + mux.Handle("POST /theme", http.HandlerFunc(setUserTheme)) portStr := ":" + strconv.Itoa(*port) log.Println("Listening on", portStr) @@ -95,3 +96,32 @@ func setUserLanguage(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, c.Value, http.StatusFound) } } + +func setUserTheme(w http.ResponseWriter, r *http.Request) { + c, err := r.Cookie("theme") + if errors.Is(err, http.ErrNoCookie) { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "No ‘theme’ cookie exists") + return + } + + var theme string + + switch c.Value { + case "dark": + theme = "light" + case "light": + theme = "dark" + default: + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "Theme ‘%s’ is invalid", c.Value) + return + } + + http.SetCookie(w, &http.Cookie{ + Name: "theme", + Value: theme, + MaxAge: math.MaxInt32, + }) + http.Redirect(w, r, r.Referer(), http.StatusFound) +} diff --git a/templates/navbar.templ b/templates/navbar.templ index f0d654c..8f156e7 100644 --- a/templates/navbar.templ +++ b/templates/navbar.templ @@ -67,7 +67,7 @@ templ navbar() {