Description
(Go1.6)
The conventional tag formatting allows some kinds of whitespace in the "value" part of the tag, but not others. Specifically, it fails quietly when there is a newline:
package main
import (
"fmt"
"reflect"
)
type Foo struct {
Bar string `key:"some value with whitespace"`
Baz string `key:"some value with
a different kind
of whitespace"`
}
func main() {
typ := reflect.TypeOf([]Foo{}).Elem()
for i := 0; i < typ.NumField(); i++ {
fmt.Printf("%d %s\n", i, typ.Field(i).Tag.Get("key"))
}
}
The output is:
0 some value with whitespace
1
as you can see in the Go Playground.
It does not make sense for "some whitespace but not others" to be allowed here, and this should be an easy fix. It would be very good to allow newlines here, as it would greatly improve the ability to format code without having to employ the workaround of writing one's own tag parser.
The canonical use case that I keep coming up against is embedding SQL into struct tags when I write DTO models, but one can think of dozens more....
eg.
type PersonNameModel struct {
db *lhqm.Connection
Create *sql.Stmt `query:"INSERT INTO PersonName(firstname,lastname,middle,preftitle)
VALUES($1,$2,$3,$4)"`
RetrieveById *sql.Stmt `query:"SELECT * FROM PersonName WHERE id=$1"`
RetreiveByLastName *sql.Stmt `query:"SELECT * FROM PersonName WHERE lastname LIKE '%'||$1||'%'"`
RetreiveByFirstName *sql.Stmt `query:"SELECT * FROM PersonName WHERE firstname LIKE '%'||$1||'%'"`
RetreiveAltnamesByPerson *sql.Stmt `query:"SELECT pn.* FROM PersonName pn, PersonAlternateName pan
WHERE pan.personId = $1
AND pan.personNameId = pn.id)"`
}
The first and last fields' queries above were not being prepared by my code that iterates over the struct fields looking for *sql.Stmt
fields with "query" tags! I have to put them all on a single line, or re-write the tag parser...