问题
I am using gorilla schema to populate a struct based on a user's form submission. My struct contains sql.NullString
and I am currently getting the following error:
schema: converter not found for sql.NullString
How can I use sql.NullString
in a struct that I want to populate with gorilla schema?
回答1:
I created a gist ( https://gist.github.com/carbocation/51b55297702c7d30d3ef ) that shows one way to approach this. You need to create a schema.Converter
for each of the four types: sql.NullString, sql.NullBool, sql.NullInt64, and sql.NullFloat64.
An example for sql.NullString:
import "database/sql"
import "reflect"
func ConvertSQLNullString(value string) reflect.Value {
v := sql.NullString{}
if err := v.Scan(value); err != nil {
return reflect.Value{}
}
return reflect.ValueOf(v)
}
Then register this with your *schema.Decoder
(usually a package global, in this case named d
):
import "database/sql"
nullString := sql.NullString{}
d.RegisterConverter(nullString, ConvertSQLNullString)
来源:https://stackoverflow.com/questions/27744493/can-i-use-gorilla-schema-with-an-sql-nullstring