Go reading struct tag

Go reading struct tag

June 21, 2020

tags
Go Programming Programming Code snippets

The following code reads a specific struct Tag by name.

import (
	"reflect"
	"strings"
	"fmt"
)

type Profile struct {
	Id            int    `validate:"numeric" json:"id"`
	First         string `validate:"required" json:"first"`
	Last          string `validate:"required" json:"last"`
	Birth         string `validate:"required" json:"birth"`
	Sex           string `validate:"required" json:"sex"`
	MaritalStatus string `validate:"required" json:"marital_status"`
	Children      int    `validate:"numeric" json:"children"`
}

func GetStructFieldValidators(data interface{}) map[string][]string {
	v := reflect.ValueOf(data)
	t := reflect.TypeOf(data)

	validators := make(map[string][]string)
	for i := 0; i < v.NumField(); i++ {
		validators[strings.ToLower(v.Type().Field(i).Name)] = []string{t.Field(i).Tag.Get("validate")}
	}
	return validators
}

func main() {
	for k, v := range GetStructFieldValidators(Profile{}){
		fmt.Println(k, v)
	}
}
birth [required]
sex [required]
maritalstatus [required]
children [numeric]
id [numeric]
first [required]
last [required]

comments powered by Disqus