问题描述
我正在使用大猩猩模式根据用户的表单提交来填充结构.我的结构包含 sql.NullString
,当前出现以下错误:
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:
模式:找不到用于sql.NullString的转换器
如何在要用大猩猩模式填充的结构中使用 sql.NullString
?
How can I use sql.NullString
in a struct that I want to populate with gorilla schema?
推荐答案
我创建了要点( https://gist.github.com/carbocation/51b55297702c7d30d3ef ),展示了一种解决此问题的方法.您需要为以下四种类型分别创建一个 schema.Converter
:sql.NullString,sql.NullBool,sql.NullInt64和sql.NullFloat64.
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.
sql.NullString的示例:
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)
}
然后使用您的 * schema.Decoder
(通常是一个全局包,在本例中为 d
)注册:
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)
这篇关于我可以将gorilla模式与sql.NullString一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!