在Go中作为字符串访问HTTP响应 [英] Access HTTP response as string in Go

查看:102
本文介绍了在Go中作为字符串访问HTTP响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析一个Web请求的响应,但是我很难以字符串的形式访问它。

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")
}

如何访问响应串? ioutil.WriteFile 正确写入对文件的响应。

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.

推荐答案

bs:= string(body)应该足以给你一个字符串。

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

从那里,您可以将其用作常规字符串。

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

有点像 in this thread

var client http.Client
resp, err := client.Get(url)
if err != nil {
    // err
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusOK {
    bodyBytes, err2 := ioutil.ReadAll(resp.Body)
    bodyString := string(bodyBytes)
}

另见 GoByExample

如下所示(并在 zzn answer ),这是一个 转换 (请参阅规范)。

请参阅 []字节(字符串)?< a>(反向问题,但适用相同结论) zzzz 提到:

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:


某些转换与转换相同,例如 uint(myIntvar),它只是重新解释位。

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

索尼娅补充道:

Sonia adds:


从字节片段中创建一个字符串,绝对需要在堆上分配字符串。不变性属性强制执行此操作。

有时,您可以使用[]字节做尽可能多的工作来优化,然后在最后创建一个字符串。 bytes.Buffer 类型通常有用。

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.

这篇关于在Go中作为字符串访问HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆