普通网友 2017-03-10 11:48
浏览 67
已采纳

从http.Get中读取内容

I'm having a tough time reading XML from a GET request in Go. I just started to learn Go and haven't found any resources on this topic. What I tried:

    response, err := http.Get(url)
        if err != nil {
            log.Fatal(err)
        } else {
            defer response.Body.Close()
             xml, _ := ioutil.ReadAll(response.Body)
            if err != nil {
                log.Fatal(err)
            }
        }

_, err := io.Copy(os.Stdout, response.Body) works but I'd like to store the XML for further processing. Any help is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dongwuge6201 2017-03-10 12:09
    关注

    What you've tried is mostly good. Few things to improve it:

    http.Get() returns an http.Response and an optional error. If there is no error, that only means that the HTTP GET operation succeeded, but the server might have responded with an error document. So you still have to check the response HTTP status code.

    Also io.ReadAll() also returns an error (besides the read data), don't forget to check that too.

    Let's wrap it in a function:

    func getXML(url string) (string, error) {
        resp, err := http.Get(url)
        if err != nil {
            return "", fmt.Errorf("GET error: %v", err)
        }
        defer resp.Body.Close()
    
        if resp.StatusCode != http.StatusOK {
            return "", fmt.Errorf("Status error: %v", resp.StatusCode)
        }
    
        data, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            return "", fmt.Errorf("Read body: %v", err)
        }
    
        return string(data), nil
    }
    

    Testing / using the above function:

    if xmlStr, err := getXML("http://somehost.com/some.xml"); err != nil {
        log.Printf("Failed to get XML: %v", err)
    } else {
        log.Println("Received XML:")
        log.Println(xmlStr)
    }
    

    Also note that it would be the same to get the content of any other responses, so it's worth not "encoding" the string conversion and return type. This one is more general:

    func getContent(url string) ([]byte, error) {
        resp, err := http.Get(url)
        if err != nil {
            return nil, fmt.Errorf("GET error: %v", err)
        }
        defer resp.Body.Close()
    
        if resp.StatusCode != http.StatusOK {
            return nil, fmt.Errorf("Status error: %v", resp.StatusCode)
        }
    
        data, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            return nil, fmt.Errorf("Read body: %v", err)
        }
    
        return data, nil
    }
    

    Using this to get an XML doc:

    if data, err := getContent("http://somehost.com/some.xml"); err != nil {
        log.Printf("Failed to get XML: %v", err)
    } else {
        log.Println("Received XML:")
        log.Println(string(data))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c