Golang net.IP.MarshalText() and UnmarshalText() functions example

package net

Golang net.IP.MarshalText() and UnmarshalText() functions usage example

 package main

 import (
 "fmt"
 "net"
 )

 func main() {

 ip4 := "127.0.0.1"

 // convert to IP type
 ipAdd4 := net.ParseIP(ip4)

 ipBytes, _ := ipAdd4.MarshalText()

 fmt.Println("MarshalText : ", string(ipBytes))

 // IP address form is accepted
 var IPointer net.IP
 dummyIP := []byte("127.0.0.1")

 err := IPointer.UnmarshalText(dummyIP)

 if err != nil {
 panic(err)
 }

 // now, try with invalid form
 errorIP := []byte("127.00.1")

 err = IPointer.UnmarshalText(errorIP)

 if err != nil {
 fmt.Println(err)
 }

 }

Output :

MarshalText : 127.0.0.1

invalid IP address: 127.00.1

References :

http://golang.org/pkg/net/#IP.UnmarshalText

http://golang.org/pkg/net/#IP.MarshalText

Advertisement