我们如何使用带有postgresql的GORM来插入ip地址的具有inet数据类型的表并从中进行选择?
这是我的型号
import (
"github.com/jackc/pgtype"
)
...
ClientIp pgtype.Inet `json:"client_ip" gorm:"type:inet;not null"`
...
我正在尝试解析字符串格式的ip地址,以便在postgresql数据库中键入pgtype.Inet
像这样插入数据库
import (
"net"
)
...
ClientIp: net.ParseIP(c.IP()),
...
我们被告知使用net
包解析ip,但这是的错误
cannot use net.ParseIP(c.IP()) (type net.IP) as type pgtype.Inet in field value
我还尝试过将net
包用于型号
import (
"net"
)
...
ClientIp net.IP `json:"client_ip" gorm:"type:inet;not null"`
...
但是不断得到这个错误
sql: Scan error on column index 16, name "client_ip": unsupported Scan, storing driver.Value type string into type *net.IP
那么我们如何使用GORM在postgresql中存储inet
值
型号:
import (
"github.com/jackc/pgtype"
)
...
ClientIp pgtype.Inet `json:"client_ip" gorm:"type:inet;not null"`
...
然后你可以像这个一样创建函数SetInet
func SetInet(ip string) pgtype.Inet {
var inet pgtype.Inet
inet.Set(ip)
return inet
}
然后您可以使用该函数设置inet:
...
ClientIp: SetInet("127.0.0.1"),
...
如果您不想创建类似的函数,您可以从包含字段pgtype.Inet
的变量中设置它
示例:
...
type Ip struct {
gorm.Model
ClientIp pgtype.Inet `gorm:"type:inet;not null"`
}
...
var ip Ip
ip.ClientIp.Set("127.0.0.1")
...