How to store ipv4 and ipv6 addresses in postgresql using GORM

Viewed 220

How do we insert and select from a table with inet datatype for ip addresses using GORM with postgresql?

here is my model

import (
    "github.com/jackc/pgtype"
)

...
ClientIp     pgtype.Inet `json:"client_ip" gorm:"type:inet;not null"`
...

I am trying to parse the ip address which is in string format to type pgtype.Inet in postgresql database like this when inserting into the database

import (
    "net"
)

...
ClientIp:     net.ParseIP(c.IP()),
...

we are told to parse the ip using net package but this is error from that

cannot use net.ParseIP(c.IP()) (type net.IP) as type pgtype.Inet in field value

I have also tried using net package for the model

import (
    "net"
)

...
ClientIp     net.IP `json:"client_ip" gorm:"type:inet;not null"`
...

but kept getting this error

sql: Scan error on column index 16, name "client_ip": unsupported Scan, storing driver.Value type string into type *net.IP

so how do we store inet values inside postgresql using GORM?

1 Answers

model :

import (
    "github.com/jackc/pgtype"
)

...
ClientIp     pgtype.Inet `json:"client_ip" gorm:"type:inet;not null"`
...

then you can create func SetInet like this

func SetInet(ip string) pgtype.Inet {
    var inet pgtype.Inet
    inet.Set(ip)
    return inet
}

then you can use that function to set inet :

...
ClientIp:     SetInet("127.0.0.1"),
...

If you don't want to create func like that you can set it from variable that contain field pgtype.Inet

example :

...
    type Ip struct {
        gorm.Model
        ClientIp pgtype.Inet `gorm:"type:inet;not null"`
    }
...
    var ip Ip

    ip.ClientIp.Set("127.0.0.1")
...

Related