在 Go 中以字符串形式访问 HTTP 响应 [英] Access HTTP response as string in Go

查看:20
本文介绍了在 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.

有点像在这个线程中
(更新后 Go 1.16 -- 2021 年第一季度 -- ioutil 弃用: ioutil.ReadAll() => io.ReadAll()):

A bit as in this thread
(updated after Go 1.16 -- Q1 2021 -- ioutil deprecation: ioutil.ReadAll() => io.ReadAll()):

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 := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    bodyString := string(bodyBytes)
    log.Info(bodyString)
}

另见GoByExample.

如下所述(以及在 zznanswer),这是一个转换(请参阅规范).
请参阅[]byte(string) 有多贵?";(相反的问题,但同样的结论适用)其中 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.

索尼娅补充说:

从字节切片中生成字符串,肯定涉及在堆上分配字符串.不变性属性强制这样做.
有时您可以通过使用 []byte 做尽可能多的工作然后在最后创建一个字符串来优化.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天全站免登陆