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 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧