可以使用gorilla schema与sql.NullString一起使用吗?

huangapple go评论152阅读模式
英文:

Can I use gorilla schema with an sql.NullString?

问题

我正在使用gorilla schema根据用户的表单提交来填充一个结构体。我的结构体包含sql.NullString,目前我遇到了以下错误:

schema: converter not found for sql.NullString

我该如何在我想要用gorilla schema填充的结构体中使用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:

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

得分: 4

我创建了一个代码片段(https://gist.github.com/carbocation/51b55297702c7d30d3ef),展示了一种处理这个问题的方法。你需要为以下四种类型创建一个 schema.Converter:sql.NullString、sql.NullBool、sql.NullInt64 和 sql.NullFloat64。

以 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)中:

import "database/sql"

nullString := sql.NullString{}
d.RegisterConverter(nullString, ConvertSQLNullString)
英文:

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)

huangapple
  • 本文由 发表于 2015年1月2日 23:32:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/27744493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定