zoukankan      html  css  js  c++  java
  • golang 对结构体进行格式化输出

    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": ""
            }
        }
    }
    

      

  • 相关阅读:
    Hamming Distance(随机算法)
    Difference Between Primes
    Pet(dfs)
    29. Divide Two Integers
    28. Implement strStr()
    25. Reverse Nodes in k-Group
    24. Swap Nodes in Pairs
    23. Merge k Sorted Lists
    22. Generate Parentheses
    19. Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/saryli/p/13073410.html
Copyright © 2011-2022 走看看