reflect StructTag Lookup For Custom Tags

reflect.StructTag.Lookup reads custom validate tags per field and distinguishes a missing tag from an empty one, which Get cannot do.

GoData Integrity

Code

gosnippet
30 lines
package main

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

type User struct {
	Name  string `validate:"required,max=64"`
	Email string `validate:"email"`
	ID    string `json:"id" validate:"required"`
}

func report(field reflect.StructField) {
	// reflect.StructTag Lookup reports ok=false for missing custom tags
	if tag, ok := field.Tag.Lookup("validate"); ok {
		opts := strings.Split(tag, ",")
		fmt.Printf("%s: %v\n", field.Name, opts)
		return
	}
	fmt.Printf("%s: no validate tag\n", field.Name)
}

func main() {
	t := reflect.TypeOf(User{})
	for i := range t.NumField() {
		report(t.Field(i))
	}
}

What the code does

Everything that moves lives in the functions report and main.

The file repeats itself only inside for i := range t.NumField().

Points of care

  • Nothing to install: every API here comes with the runtime itself.

Applying it

The main signature, verbatim, is func report(field reflect.StructField)

main sequences report; executing the file runs that flow once.

Statements that decide the outcome

func report(field reflect.StructField) {
	// reflect.StructTag Lookup reports ok=false for missing custom tags
	if tag, ok := field.Tag.Lookup("validate"); ok {
		opts := strings.Split(tag, ",")
		fmt.Printf("%s: %v\n", field.Name, opts)
		return
	}
	fmt.Printf("%s: no validate tag\n", field.Name)
}
for i := range t.NumField() {
	report(t.Field(i))
}

Interactive Tools for This Topic

FAQ

How do you run reflect StructTag Lookup For Custom Tags?
The file is self-contained: run it directly, no dependencies to install beforehand.