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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run reflect StructTag Lookup For Custom Tags?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.