能夠使用數據庫
`return fmt.Sprintf("%+v", *conf) `json
來打印結構體,包括結構體的key值。可是因爲結構體內容較多,都在一行,因此但願能夠格式化輸出結構體。服務器
其實能夠接住結構體對應的默認json結構,來進行json的格式化blog
package main import ( "bytes" "encoding/json" "fmt" ) type RedisConfig struct { IP string PORT string AUTH int PASS string } type DbConfig struct { Host string Port int Uid string Pwd string DbName string } //Config 遊戲服務器的配置 type Config struct { ServerId int Port int //端口號 Redis *RedisConfig DbConfigs map[string]*DbConfig //若是配置多個數據庫源,則用逗號分隔源的名字 callbacks []func() } func (conf *Config) String() string { b, err := json.Marshal(*conf) if err != nil { return fmt.Sprintf("%+v", *conf) } var out bytes.Buffer err = json.Indent(&out, b, "", " ") if err != nil { return fmt.Sprintf("%+v", *conf) } return out.String() } func main(){ conf:=Config{ ServerId:1, Port:8080, Redis:&RedisConfig{}, DbConfigs: map[string]*DbConfig{ "maindb": &DbConfig{ Host:"127.0.0.1", } , }, } fmt.Println("Config:",conf.String()) }
輸出結果爲:遊戲
Config: { "ServerId": 1, "Port": 8080, "Redis": { "IP": "", "PORT": "", "AUTH": 0, "PASS": "" }, "DbConfigs": { "maindb": { "Host": "127.0.0.1", "Port": 0, "Uid": "", "Pwd": "", "DbName": "" } } }
符合預期,原本想的複雜了,想要 利用reflect反射來本身作這個事情,可是默認的json反射就把這個給作了,好好好!string