Can I use gorilla schema with an sql.NullString?

∥☆過路亽.° 提交于 2019-12-11 02:53:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!