Move all theme environment variable logic to a utils function

Move theme environment variable logic to a utils function and update routes to use it.

* Add `GetThemeFromEnv` function in `src/utils/theme.go` to derive the theme from environment variables and default to "auto" if not set.
* Update `src/routes/home.go` to import and use `GetThemeFromEnv` in the `GetHome` function.
* Update `src/routes/options.go` to import and use `GetThemeFromEnv` in the `ChangeOptions` function.
* Update `src/routes/question.go` to import and use `GetThemeFromEnv` in the `ViewQuestion` function.


---

For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/httpjamesm/AnonymousOverflow/pull/145?shareId=a0dab6f3-027c-4f6e-85fe-60e7675d0e70).
This commit is contained in:
httpjamesm 2024-07-25 10:03:55 -07:00
parent 31390edfc4
commit 578e4b173e
4 changed files with 16 additions and 15 deletions

View file

@ -2,6 +2,7 @@ package routes
import ( import (
"anonymousoverflow/config" "anonymousoverflow/config"
"anonymousoverflow/src/utils"
"fmt" "fmt"
"os" "os"
"regexp" "regexp"
@ -11,10 +12,7 @@ import (
) )
func GetHome(c *gin.Context) { func GetHome(c *gin.Context) {
theme := os.Getenv("THEME") theme := utils.GetThemeFromEnv()
if theme == "" {
theme = "auto"
}
c.HTML(200, "home.html", gin.H{ c.HTML(200, "home.html", gin.H{
"version": config.Version, "version": config.Version,
"theme": theme, "theme": theme,

View file

@ -2,10 +2,8 @@ package routes
import ( import (
"anonymousoverflow/config" "anonymousoverflow/config"
"anonymousoverflow/src/utils"
"fmt" "fmt"
"os"
"github.com/gin-gonic/gin"
) )
func ChangeOptions(c *gin.Context) { func ChangeOptions(c *gin.Context) {
@ -18,10 +16,7 @@ func ChangeOptions(c *gin.Context) {
text = "enabled" text = "enabled"
} }
c.SetCookie("disable_images", fmt.Sprintf("%t", !c.MustGet("disable_images").(bool)), 60*60*24*365*10, "/", "", false, true) c.SetCookie("disable_images", fmt.Sprintf("%t", !c.MustGet("disable_images").(bool)), 60*60*24*365*10, "/", "", false, true)
theme := os.Getenv("THEME") theme := utils.GetThemeFromEnv()
if theme == "" {
theme = "auto"
}
c.HTML(200, "home.html", gin.H{ c.HTML(200, "home.html", gin.H{
"successMessage": "Images are now " + text, "successMessage": "Images are now " + text,
"version": config.Version, "version": config.Version,

View file

@ -101,10 +101,7 @@ func ViewQuestion(c *gin.Context) {
imagePolicy = "'self'" imagePolicy = "'self'"
} }
theme := os.Getenv("THEME") theme := utils.GetThemeFromEnv()
if theme == "" {
theme = "auto"
}
c.HTML(200, "question.html", gin.H{ c.HTML(200, "question.html", gin.H{
"question": newFilteredQuestion, "question": newFilteredQuestion,

11
src/utils/theme.go Normal file
View file

@ -0,0 +1,11 @@
package utils
import "os"
func GetThemeFromEnv() string {
theme := os.Getenv("THEME")
if theme == "" {
theme = "auto"
}
return theme
}