I want to escape a backtick inside a Go struct tag. For example in the code below:
type User struct {
email string `validate: "regexp=`"`
password string `validate: "min=8"`
}
Backtick strings are analogues of any multiline raw string within Python or else Scala: r""" text""" or within JavaScript: String. raw`Hello\u000A!` They are useful: For keeping huge text inside. For regular expressions, while you own many of backslashes.
In the Go Language Specification, it mentions a brief overview of tags: A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. The tags are made visible through a reflection interface but are otherwise ignored.
You can use regular quotes. You'll just have to escape more characters, especially the quotes around the value part of the struct tag.
type User struct {
Email string "validate:\"regexp=`\""
Password string `validate:"min=8"`
}
And verify the tag value with reflection:
func main() {
s := reflect.ValueOf(&User{}).Elem()
fmt.Println(s.Type().Field(0))
}
Outputs:
{Email string validate:"regexp=`" 0 [0] false}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With