(去新手) 我有一些像这样的代码:
func (c *clientImpl) queryHost(qtype string, page int) (io.ReadCloser, error) {
queryURI := c.URL + "/api/query"
req, _ := http.NewRequest(http.MethodGet, queryURI, nil)
req.Header.Add(authHeaderName, authToken)
req.Header.Add("Accept", accept)
q := req.URL.Query()
q.Add("type", qtype)
q.Add("pageSize", pageSize)
q.Add("page", strconv.Itoa(page))
req.URL.RawQuery = q.Encode()
resp, err := c.client.Do(req) //*http.Client
if err != nil {
return nil, utils.NestedError("Error in querying Host", err)
}
return resp.Body, nil
}
然后这样叫:
body, err := c.queryHost(myQType, i)
if err != nil {
log.Printf("Error while trying to get page %v - %v \n", i, err)
return err
}
defer body.Close()
var qResult myQueryResult
err = xml.NewDecoder(body).Decode(&myQueryResult)
if err != nil {
log.Printf("Error while decoding page %v - %v \n", i, err)
return utils.NestedError("Error in decoding response body xml", err)
}
我想记录未能处理的原始xml,但由于这是ReadCloser
并且一旦读取,就无法再次读取(或者我错了吗?)。有没有办法可以得到这个,或者我是否必须在某处存储初始响应并传递副本?
答案 0 :(得分:4)
使用io/ioutil
ReadAll
defer body.Close()
data, err := ioutil.ReadAll(body)
然后解散
err = xml.Unmarshal(data, &qResult)
您可以记录数据以检查原始xml。
答案 1 :(得分:0)
对于http回复,您可以使用httputil个包DumpResponse:
链接示例:
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/http/httputil"
)
func main() {
const body = "Go is a general-purpose language designed with systems programming in mind."
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Date", "Wed, 19 Jul 1972 19:00:00 GMT")
fmt.Fprintln(w, body)
}))
defer ts.Close()
resp, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%q", dump)
}