Can I use gorilla schema with an sql.NullString?

2019-07-11 19:08发布

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条回答
等我变得足够好
2楼-- · 2019-07-11 19:28

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)
查看更多
登录 后发表回答