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.3k Golang : Get current file path of a file or executable
+7.5k Golang : How to handle file size larger than available memory panic issue
+17k Golang : Get number of CPU cores
+18.7k Golang : Implement getters and setters
+7.8k Golang : Scan files for certain pattern and rename part of the files
+7.3k Golang : alternative to os.Exit() function
+7.5k Golang : Create zip/ePub file without compression(use Store algorithm)
+5.6k Golang : Shortening import identifier
+7.2k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+9.2k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+9.9k Golang : ffmpeg with os/exec.Command() returns non-zero status
+6.2k PHP : Get client IP address