可以使用
`return fmt.Sprintf("%+v", *conf) `
來打印結構體,包括結構體的key值。但是由於結構體內容較多,都在一行,所以希望可以格式化輸出結構體。
其實可以接住結構體對應的默認json結構,來進行json的格式化
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反射就把這個給做了,好好好!
