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
+25.9k Golang : How to read integer value from standard input ?
+19.3k Golang : Get host name or domain name from IP address
+16.4k Golang : How to implement two-factor authentication?
+8.6k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+14k Golang : Google Drive API upload and rename example
+27.7k PHP : Count number of JSON items/objects
+6k PHP : How to check if an array is empty ?
+11.9k Golang : Convert decimal number(integer) to IPv4 address
+7.7k Golang : get the current working directory of a running program
+10k Golang : Setting variable value with ldflags
+29.5k Golang : Login(Authenticate) with Facebook example
+5.7k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example