Code
func GetStructureDataInfo(itf interface{}, structName string) string {
structType := reflect.TypeOf(itf)
if structType.Kind() == reflect.Ptr {
structType = structType.Elem()
}
if structType.Kind() != reflect.Struct {
panic("can not use not-structure arguments" +
" in function \"GetStructureDataInfo\"")
}
structValue := reflect.ValueOf(itf)
info := fmt.Sprintf("\t%s {\n", /*Green(*/structName/*)*/)
for i := 0; i < structType.NumField(); i++ {
// 若想层层展开结构体,针对reflect.Struct进行递归调用
typeInfo := structType.Field(i).Name
valueInfo := structValue.Field(i)
info += fmt.Sprintf("\t\t%20s:\t %v\n", typeInfo, valueInfo)
}
info += "\t}"
return info
}
Example
var ServerConfig = struct {
// Maximum size of single upload file
MaxUploadSize int
// Maximum overall request size
MaxRequestBodySize int
// Root directory of uploaded files
UploadPath string
// File Operating Port
OperationPort string
// File Visit port
VisitPort string
// Operation certificate
OperationToken string
// Generate a file directory index
GenerateIndexPages bool
} {}
func TestFromatStructureDataOutput(t *testing.T) {
fmt.Println(/*logUtil.*/GetStructureDataInfo(ServerConfig, "ServerConfig"))
fmt.Println(GetStructureDataInfo(&ServerConfig, "ServerConfig"))
}
ServerConfig {
MaxUploadSize: 20
MaxRequestBodySize: 30
UploadPath: upload
OperationPort: 1919
VisitPort: 2020
OperationToken: nsp
GenerateIndexPages: true
}
ServerConfig {
MaxUploadSize: 20
MaxRequestBodySize: 30
UploadPath: upload
OperationPort: 1919
VisitPort: 2020
OperationToken: nsp
GenerateIndexPages: true
}
版权声明:本文为qq_35587463原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。