You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
821 B
Go

package main
import (
"encoding/json"
"errors"
"net"
)
// IP is the net.IP with a version string to allow storing the version
type IP struct {
net.IP
version string
}
// NewIP returns a new instance of an IP address
func NewIP(addr string) (*IP, error) {
parsedIP := net.ParseIP(addr)
if parsedIP == nil {
return nil, errors.New("Could not parse address " + addr)
}
result := &IP{parsedIP, ""}
if result.isV6() {
result.version = "v6"
} else {
result.version = "v4"
}
return result, nil
}
// MarshalJSON for marshalling ip to json for response
func (ip *IP) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
IP string `json:"ip"`
Version string `json:"version"`
}{
IP: ip.String(),
Version: ip.version,
})
}
func (ip *IP) isV6() bool {
return ip.To4() == nil
}