Created
June 27, 2021 13:53
-
-
Save raifpy/cd8c4f2494dc0e49c3de4c7ac5ba7e61 to your computer and use it in GitHub Desktop.
Golang parse Struct tag example
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 main | |
import ( | |
"fmt" | |
"log" | |
"reflect" | |
) | |
type T struct { | |
Abc string `böhöhöyt:"kenya" required:"true"` // supports non ascii | |
Cba string `böhöhöyt:"konya" required:"false"` | |
smallcase string `böhöhöyt:"karaambar" required:"true"` | |
} | |
func main() { | |
var te = T{ | |
//Abc: "Merhaba Dünya!", | |
Cba: "!Dünya Merhaba", | |
} | |
fmt.Println("te:", te) | |
tereflect := reflect.TypeOf(te) | |
fmt.Println("te type: ", tereflect.String()) // type | |
value := reflect.ValueOf(te) | |
for i := 0; i < tereflect.NumField(); i++ { | |
field := tereflect.Field(i) | |
switch field.Type.Kind() { | |
case reflect.String: | |
if field.Tag.Get("required") == "true" && value.Field(i).String() == "" { | |
log.Println("required but empty!", field.Name) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment