doulangbi6869 2016-07-30 11:58
浏览 79
已采纳

在Go中以字符串形式访问HTTP响应

I'd like to parse the response of a web request, but I'm getting trouble accessing it as string.

func main() {
    resp, err := http.Get("http://google.hu/")
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)

    ioutil.WriteFile("dump", body, 0600)

    for i:= 0; i < len(body); i++ {
        fmt.Println( body[i] ) // This logs uint8 and prints numbers
    }

    fmt.Println( reflect.TypeOf(body) )
    fmt.Println("done")
}

How can I access the response as string? ioutil.WriteFile writes correctly the response to a file.

I've already checked the package reference but it's not really helpful.

  • 写回答

3条回答 默认 最新

  • dpf5207 2016-07-30 12:00
    关注

    bs := string(body) should be enough to give you a string.

    From there, you can use it as a regular string.

    A bit as in this thread:

    var client http.Client
    resp, err := client.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    
    if resp.StatusCode == http.StatusOK {
        bodyBytes, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        bodyString := string(bodyBytes)
        log.Info(bodyString)
    }
    

    See also GoByExample.

    As commented below (and in zzn's answer), this is a conversion (see spec).
    See "How expensive is []byte(string)?" (reverse problem, but the same conclusion apply) where zzzz mentioned:

    Some conversions are the same as a cast, like uint(myIntvar), which just reinterprets the bits in place.

    Sonia adds:

    Making a string out of a byte slice, definitely involves allocating the string on the heap. The immutability property forces this.
    Sometimes you can optimize by doing as much work as possible with []byte and then creating a string at the end. The bytes.Buffer type is often useful.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度