15/08/2024 - GO
In this example we are going to extract struct field names and print the result. It can sometimes be useful to manage application configs or secrets further down the line.
package main
import (
"fmt"
"reflect"
)
func main() {
var str Struct
fields := str.Fields(Config{}, "/")
for _, field := range fields {
fmt.Println(field)
}
}
type Struct struct {
fields []string
separator string
}
func (s *Struct) Fields(source any, separator string) []string {
s.separator = separator
s.extract(reflect.ValueOf(source), "")
return s.fields
}
func (s *Struct) extract(source reflect.Value, prefix string) {
for i := 0; i < source.NumField(); i++ {
field := source.Field(i)
name := source.Type().Field(i).Name
if field.Kind() == reflect.Struct {
s.extract(field, prefix+name+s.separator)
continue
}
s.fields = append(s.fields, prefix+name)
}
}
type Config struct {
ServiceName string
Addresses []string
Logger struct {
Level string
}
HTTP struct {
Server struct {
Host string
Port int
Request struct {
Timeout string
Size int
}
}
}
External
}
type External struct {
ID string
Level struct {
Severity string
}
}
ServiceName
Addresses
Logger/Level
HTTP/Server/Host
HTTP/Server/Port
HTTP/Server/Request/Timeout
HTTP/Server/Request/Size
External/ID
External/Level/Severity