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 :
Advertisement
Something interesting
Tutorials
+31.5k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+10.3k Golang : Wait and sync.WaitGroup example
+7.7k Gogland : Where to put source code files in package directory for rookie
+31.1k Golang : Calculate percentage change of two values
+10.6k Golang : Bubble sort example
+15.6k Golang : ROT47 (Caesar cipher by 47 characters) example
+6.3k Golang : Calculate US Dollar Index (DXY)
+10k Golang : Setting variable value with ldflags
+16.1k Golang : Generate universally unique identifier(UUID) example
+36.6k Golang : Validate IP address
+7.1k Golang : A simple forex opportunities scanner
+5.8k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error