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
+7.9k Golang : Ways to recover memory during run time.
+18.5k Golang : Set, Get and List environment variables
+11k How to test Facebook App on localhost ?
+10.1k Golang : Test a slice of integers for odd and even numbers
+9.9k Golang : Check if user agent is a robot or crawler example
+5.5k Golang : Stop goroutine without channel
+10.9k Golang : Sieve of Eratosthenes algorithm
+11.3k Golang : Characters limiter example
+10.2k Golang : How to get quoted string into another string?
+9.4k Golang : Timeout example
+19.9k Golang : Count JSON objects and convert to slice/array
+26.1k Mac/Linux and Golang : Fix bind: address already in use error