2015-12-03 81 views
0

XML API返回我試圖解析從API的XML響應,並且當呼叫fmt.Println並通過響應身體,我得到一個奇怪的字符串:轉到:奇怪的編碼字符串

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

我已經確認我可以使用API​​並按預期得到XML。 (我也得到了相同的迴應,發送GET請求與Postman Chrome擴展。)這是一個編碼問題?

下面是相關代碼:

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>} 

回答

2

http.Response的身體是一個io.ReaderCloser。您看到的奇數輸出是用作響應主體的結構體字段的值。

如果您想要打印出實際內容,您必須先從身體中讀取它。

嘗試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. 
} 
+0

謝謝!這讓我如預期的XML。但是,即使'xml.Unmarshal'採用'[]字節',當我通過它時,它似乎沒有用數據('main'的最後一行)填充'Album'結構。有什麼想法嗎? – nickcoxdotme

+0

我也雙重和三重檢查了XML結構。 – nickcoxdotme

+0

您可以將XML添加到您的原始問題嗎?很難幫助排除故障,如果我們不知道xml解析器的輸入 –