Last active
March 25, 2021 06:31
-
-
Save diabloneo/f607399581f8a7eea6ac3e1f596fa479 to your computer and use it in GitHub Desktop.
Fill a Golang struct's string fields' values according with fieldss names.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package common | |
import ( | |
"fmt" | |
"go/token" | |
"reflect" | |
) | |
// FillStructString set values of string fields of a struct to the field names. | |
func FillStructString(value interface{}) { | |
v := reflect.ValueOf(value) | |
if v.Kind() != reflect.Ptr { | |
panic("require a pointer") | |
} | |
v = v.Elem() | |
if v.Kind() != reflect.Struct { | |
panic("require pointer to a struct") | |
} | |
typ := v.Type() | |
for i := 0; i < typ.NumField(); i++ { | |
field := typ.Field(i) | |
if field.Anonymous { | |
FillStructString(v.Field(i).Addr().Interface()) | |
continue | |
} | |
if field.Type.Kind() != reflect.String { | |
continue | |
} | |
if !token.IsExported(field.Name) { | |
continue | |
} | |
v.Field(i).SetString(field.Name) | |
} | |
} | |
// CommonStatus are status shared by resources. | |
type CommonStatus struct { | |
Active string | |
Building string | |
BuildingError string | |
Deleting string | |
DeletingError string | |
Deleted string | |
} | |
// DataSourceStatusDefinition defines status. | |
type DataSourceStatusDefinition struct { | |
CommonStatus | |
Initializing string | |
} | |
// DataSourceStatus definitions. | |
var DataSourceStatus = new(DataSourceStatusDefinition) | |
func init() { | |
common.FillStructString(DataSourceStatus) | |
fmt.Printf("%+v\n", DataSourceStatus) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment