Golang应用程序如何支持暗黑模式
Golang应用程序如何支持暗黑模式 继续讨论自 新版 Discourse 支持深色模式:
是否有可能将网站更新到支持深色模式的最新 Discourse 版本?
现在许多 Discourse 网站都支持深色模式。 是否有计划更新此网站?
2 回复
您好, 前往管理员仪表板 (/admin)。
导航到 自定义 → 主题。
您可以:
启用 Discourse 自带的默认深色主题。
或者浏览并安装自定义的深色主题。
通过启用 /admin/site_settings 下的“允许用户选择主题”设置,允许用户在其偏好设置中选择主题。
此致, Darif
更多关于Golang应用程序如何支持暗黑模式的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
目前Go语言本身不直接提供暗黑模式支持,这通常由前端技术实现。不过,可以通过Go后端提供配置接口,结合前端实现暗黑模式切换。以下是一个示例,展示如何通过Go的HTTP服务器提供暗黑模式配置的API端点:
package main
import (
"encoding/json"
"net/http"
)
// ThemeConfig 表示主题配置
type ThemeConfig struct {
DarkMode bool `json:"darkMode"`
}
var currentTheme = ThemeConfig{DarkMode: false}
// getThemeHandler 返回当前主题配置
func getThemeHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(currentTheme)
}
// updateThemeHandler 更新主题配置
func updateThemeHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var config ThemeConfig
if err := json.NewDecoder(r.Body).Decode(&config); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
currentTheme = config
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(currentTheme)
}
func main() {
http.HandleFunc("/api/theme", getThemeHandler)
http.HandleFunc("/api/theme/update", updateThemeHandler)
http.ListenAndServe(":8080", nil)
}
前端可以通过JavaScript调用这些API来获取和更新主题设置,然后应用相应的CSS类实现暗黑模式。例如,使用fetch更新主题:
fetch('/api/theme/update', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({darkMode: true})
});
在实际部署中,可能需要结合数据库存储用户偏好,并使用中间件处理认证。

