Go structure format output

Time:2021-5-4

When locating problems in software system, log is indispensable, but when a system has many functions and needs to print a lot of logs, at this time, in order to improve the efficiency of browsing log, easy to read output format is essential.

Printing structure is the longest operation when printing log, but it is not easy to read when the structure content is more than one line. In go, the structure can be easily converted to JSON, so we can use JSON to complete the formatted output of struct.

Print on one line, use% + V to display the structure field name:

package main

import (
	"fmt"
)

//Student information
type Student struct {
	Name  string
	Addr  HomeInfo
	M   map[string]string
}

//Homeinfo home address
type HomeInfo struct {
	Province   string
	City     string
	County    string
	Street    string
	DetailedAddr string
}

var student = Student{
	Name: "dablelv",
	Addr: HomeInfo{
		Province:   "Guangdong",
		City:     "Shenzhen",
		County:    "Baoan",
		Street:    "Xixiang",
		DetailedAddr: "Shengtianqi",
	},
	M: map[string]string{
		"hobby": "pingpopng",
	},
}

func main() {
	fmt.Printf("student=%+v\n", student)
}

Operation output:

student={Name:cat Addr:{Province:Guangdong City:Shenzhen County:Baoan Street:Xixiang DetailedAddr:Shengtianqi} M:map[hobby:pingpopng]}

Output formatted JSON string:


func main() {
	bs, _ := json.Marshal(student)
	var out bytes.Buffer
	json.Indent(&out, bs, "", "\t")
	fmt.Printf("student=%v\n", out.String())
}

Running output results:

student={
“Name”: “cat”,
“Addr”: {
“Province”: “Guangdong”,
“City”: “Shenzhen”,
“County”: “Baoan”,
“Street”: “Xixiang”,
“DetailedAddr”: “Shengtianqi”
},
“M”: {
“hobby”: “pingpopng”
}
}

Converting strutc to JSON string and then formatting the output greatly increases the readability.

The conversion function has been added to the personal go toolkit go huge util. The example is as follows:


package main

import (
	"fmt"
  huge "github.com/dablelv/go-huge-util"
)

func main() {
	s, _ := huge.ToFormattedJSON(&student)
	fmt.Printf("student=%v\n", s)
}

Operation output:

student={
“Name”: “cat”,
“Addr”: {
“Province”: “Guangdong”,
“City”: “Shenzhen”,
“County”: “Baoan”,
“Street”: “Xixiang”,
“DetailedAddr”: “Shengtianqi”
},
“M”: {
“hobby”: “pingpopng”
}
}

The above is a detailed explanation of go structure format output. For more information about go structure format output, please pay attention to other related articles of developer!

Recommended Today

Large scale distributed storage system: Principle Analysis and architecture practice.pdf

Focus on “Java back end technology stack” Reply to “interview” for full interview information Distributed storage system, which stores data in multiple independent devices. Traditional network storage system uses centralized storage server to store all data. Storage server becomes the bottleneck of system performance and the focus of reliability and security, which can not meet […]