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
+18.1k Golang : Convert IPv4 address to decimal number(base 10) or integer
+10.5k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+5.4k Python : Delay with time.sleep() function example
+12.3k Golang : How to display image file or expose CSS, JS files from localhost?
+5k Golang : Constant and variable names in native language
+13.4k Golang : Get constant name from value
+19.2k Golang : Check if directory exist and create if does not exist
+9.9k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+4.7k Javascript : Access JSON data example
+6.5k Golang : Handling image beyond OpenCV video capture boundary