douceng7070 2016-08-06 19:16
浏览 130
已采纳

如何在Golang中处理纯文本HTTP Get响应?

I am making an HTTP GET request to an endpoint that returns a plain text response.

How do I grab the string of the plain text response?

My code looks like the following:

    url := "http://someurl.com"
    response,err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()

    responseString := //NOT SURE HOW TO GRAB THE PLAIN TEXT STRING
  • 写回答

3条回答 默认 最新

  • duanhuang2150 2016-08-06 19:23
    关注

    Response of the body can be read using any method that could read data from incoming byte stream. Simplest of them is ReadAll function provided in ioutil package.

    responseData,err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    

    It will give you API response in []byte. If response is plain text you can easily convert it into string using type conversion:

    responseString := string(responseData)
    

    And Check the result

    fmt.Println(responseString)
    

    Sample Program:

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "log"
        "net/http"
    )
    
    func main() {
        url := "http://country.io/capital.json"
        response, err := http.Get(url)
        if err != nil {
            log.Fatal(err)
        }
        defer response.Body.Close()
    
        responseData, err := ioutil.ReadAll(response.Body)
        if err != nil {
            log.Fatal(err)
        }
    
        responseString := string(responseData)
    
        fmt.Println(responseString)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献