Go:XML API 返回奇怪编码的字符串

标签 go

我正在尝试解析来自 API 的 XML 响应,当调用 fmt.Println 时并传递响应主体,我得到一个奇怪的字符串:

&{0xc8200e6140 {0 0} false <nil> 0xc2030 0xc1fd0}

我已经确认我可以 curl API 并按预期获取 XML。 (使用 Postman Chrome 扩展程序发送 GET 请求时,我也收到了相同的响应。)这是编码问题吗?

相关代码如下:

type Album struct {
    Title     string `xml:"album>name"`
    Artist    string `xml:"album>artist>name"`
    PlayCount uint64 `xml:"album>playcount"`
}

const lastFMAPIKey string = "<My api key>"
const APIURL string = "http://ws.audioscrobbler.com/2.0/"

func perror(err error) {
    if err != nil {
        panic(err)
    }
}

func getListeningInfo(url string) []byte {
    resp, err := http.Get(url)
    perror(err)
    defer resp.Body.Close()
    // this is the line that prints the string above
    fmt.Println(resp.Body)
    body, err2 := ioutil.ReadAll(resp.Body)
    perror(err2)
    return body
}

func main() {
    url := APIURL + "?method=user.getTopAlbums&user=iamnicholascox&period=1month&limit=1&api_key=" + lastFMAPIKey
    album := Album{}
    err := xml.Unmarshal(getListeningInfo(url), &album)
    perror(err)
    fmt.Printf(album.Artist)
}

作为引用,打印出来resp而不仅仅是 resp.Body给出这个:

{200 OK 200 HTTP/1.1 1 1 map[Ntcoent-Length:[871]
Connection:[keep-alive] Access-Control-Max-Age:[86400]
Cache-Control:[private] Date:[Thu, 03 Dec 2015 05:16:34 GMT]
Content-Type:[text/xml; charset=UTF-8]
Access-Control-Request-Headers:[Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date,
Content-Type, X-Atmosphere-Transport, *]
Access-Control-Allow-Methods:[POST, GET, OPTIONS]
Access-Control-Allow-Origin:[*]
Server:[openresty/1.7.7.2]]
0xc8200f6040 -1 [] false map[] 0xc8200b8000 <nil>}

最佳答案

http.Response的主体是一个 io.ReaderCloser。您看到的奇怪输出是用作响应主体的结构字段的值。

如果要打印出实际内容,必须先从Body中读取。

试试 ioutil。 ReadAll通过做:

b, err := ioutil.ReadAll(resp.Body) // b is a []byte here
if err != nil { 
   fmt.Println("Got error:",err)
} else {
    fmt.Println(string(b)) // convert []byte to string for printing to the screen.
}

关于Go:XML API 返回奇怪编码的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34058531/

相关文章:

go - 扫描 github.com/golang/protobuf/proto/testdata : cannot find package "." 时出错

go - 如何在 Golang 中以编程方式将进程(应用程序)优先级从“正常”更改为“低”

go - 在 Go 中引用 GORM 自动生成的字段

go - 抑制从包生成的错误消息

go - 将固定长度的数组传递给函数

go - 为什么golang时间功能在某些日期会失败

reflection - 将字符串值转换为函数调用

go - 用于接口(interface)及其实现的自定义 UnmarshalYAML 接口(interface)

go - Go 如何将 3 字节序列转换为适当的 Unicode 字符?

go - 如何在专用服务器上运行多个 Golang 应用程序?