golang 对结构体进行格式化输出

左心房为你撑大大i 提交于 2020-08-11 05:03:24
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         `json:"redis" bson:"redis"`
	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": ""
        }
    }
}

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!