douman6679 2016-09-09 12:30
浏览 13
已采纳

解码失败时获取原始XML

(go newbie here) I have some code like this:

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
}

And then called like this:

body, err := c.queryHost(myQType, i)
        if err != nil {
            log.Printf("Error while trying to get page %v - %v 
", 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 
", i, err)
            return utils.NestedError("Error in decoding response body xml", err)
        }

I want to log the original xml that was failed to be processed, but since this is a ReadCloser and once read, it cannot be read again (or am I wrong?). Is there a way I can get this, or do I have to store the initial response somewhere and pass copies around?

  • 写回答

2条回答 默认 最新

  • dongwu9170 2016-09-09 12:42
    关注
    1. Read bytes with io/ioutil ReadAll

      defer body.Close()

      data, err := ioutil.ReadAll(body)

    2. Then unmarshal

      err = xml.Unmarshal(data, &qResult)

    You can log data for checking original xml.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配