drasebt1835 2014-06-09 09:53
浏览 10
已采纳

为什么去写000 / s而不是字符串?

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.

Play it for me!

  • 写回答

1条回答 默认 最新

  • dtbi27903 2014-06-09 10:16
    关注

    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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退