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
+40.1k Golang : UDP client server read write example
+14.4k Golang : How to filter a map's elements for faster lookup
+43.3k Golang : Convert []byte to image
+11.5k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+6.1k Golang : Dealing with backquote
+9.4k Golang : Scramble and unscramble text message by randomly replacing words
+22.6k Generate checksum for a file in Go
+7.3k Golang : File system scanning
+14.6k Golang : Send email with attachment(RFC2822) using Gmail API example
+6.1k Java : Human readable password generator
+28k Golang : Move file to another directory
+13.3k Golang : Date and Time formatting