9

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"`

}

Victor Timofei
  • 334
  • 4
  • 13
  • 2
    Does this answer your question? [How to escape back ticks](https://stackoverflow.com/questions/21198980/how-to-escape-back-ticks) – The Fool May 08 '20 at 15:13
  • I cannot concat strings in struct tags. I get this error `build command-line-arguments: cannot load gopkg.in/validator.v2: module gopkg.in/validator.v2: Get https://proxy.golang.org/gopkg.in/validator.v2/@v/list: unexpected EOF ` – Victor Timofei May 08 '20 at 15:16
  • 3
    This is not a duplicate of the linked question: escaping backticks in struct tags cannot be done with any of the answers listed in that question. – Marc May 09 '20 at 05:21

1 Answers1

9

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}
Marc
  • 19,394
  • 6
  • 47
  • 51