For some reasons go encodes the string like bytes and I'm wondering if it's a go bug. See the code below:
ip, _, err := net.ParseCIDR(cidr)
if err!=nil{
log.Panicf("can't parse cidr %s, err was %v", cidr, err)
}
type Ip struct{
Ip string
}
ips := string(ip)
j:= Ip{
Ip: ips,
}
b, err := json.Marshal(j)
if err != nil {
log.Printf("error:", err)
}
fmt.Fprintln(w, string(b))
It prints:
{"Ip":"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\ufffd\ufffd\ufffd\ufffd\u0007+"}
I'm running Go from epel repository ( redhat ). I also made a snippet which returns similar results.
This happens because you are treating a sequence of IP address bytes as a raw string.
The net.IP
value returned by net.ParseCIDR
has a .String()
method you should call, instead of doing string(ip)
.
Try this instead:
package main
import (
"encoding/json"
"fmt"
"log"
"net"
)
func main() {
cidr := "172.162.21.84/32"
ip, _, err := net.ParseCIDR(cidr)
if err != nil {
log.Panicf("can't parse cidr %s, err was %v", cidr, err)
}
type Ip struct {
Ip string
}
fmt.Printf("%T: %v
", ip, ip)
j := Ip{
Ip: ip.String(),
}
b, err := json.Marshal(j)
if err != nil {
log.Printf("error:", err)
}
fmt.Println(string(b))
}