YiTao/service/common_service.go
2024-11-09 14:59:27 +08:00

50 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package service
import (
"fmt"
"strings"
"yitao/model"
"encoding/json"
)
type CommonService struct{}
type TypeSetting map[string]string
type TypeSettings map[string]TypeSetting
func (c *CommonService) GetSetting(key string) TypeSetting {
settings_json := model.RedisRemember("nexus_settings_in_nexus", 600, func() interface{} {
j, _ := json.Marshal(c.GetSettingsFromDB())
return j
})
m := make(TypeSettings)
json.Unmarshal([]byte(settings_json), &m)
return m[key]
}
func (c *CommonService) GetSettingsFromDB() TypeSettings {
// settings 表中的两个字段name 和 value把他们读取出来再组装成一个 map
var results []struct {
Name string
Value string
}
model.DB.Table("settings").Select("name", "value").Find(&results)
// 从 results 中取出 name 和 value 组装成一个 map
// 其中 name 的格式是 xxx.yyy ,那么就是一个嵌套的 map
settings := make(TypeSettings)
for _, result := range results {
keys := strings.Split(result.Name, ".")
if len(keys) == 1 {
settings[keys[0]] = TypeSetting{keys[0]: result.Value}
} else {
if _, ok := settings[keys[0]]; !ok {
settings[keys[0]] = TypeSetting{}
}
settings[keys[0]][keys[1]] = result.Value
}
}
fmt.Printf("settings: %v\n", settings)
return settings
}