下载包
go get -u github.com/redis/go-redis/v9
配置文件:config.json
{
"redis": {
"host": "192.168.4.3:6379",
"db": "0"
}
}
config.go
package config
import (
"encoding/json"
"log"
"os"
)
var c *config
type config struct {
Redis `json:"redis"`
}
type Redis struct {
DB int `json:"db"`
Host string `json:"host"`
}
func Instance() *config {
if c == nil {
InitConfig()
}
return c
}
func InitConfig() {
file, _ := os.Open("../config.json")
defer file.Close()
decoder := json.NewDecoder(file)
if err := decoder.Decode(&c); err != nil {
log.Fatal(err)
return
}
}
测试:main.go
package config
import (
"fmt"
)
func main() {
InitConfig()
config := Instance()
fmt.Printf("%+v\n", config.Redis)
}