我想解析Web请求的响应,但我无法将其作为字符串访问.

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将响应正确写入文件.

我已经判断了软件包参考,但它没有真正的帮助.

推荐答案

bs := string(body)应该足够给你一根绳子了.

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

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.

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),它只是重新解释到位的位.

Sonia增加了:

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相关问答推荐

Go Fiber和HTMX—HX—Trigger header被更改为HX—Trigger,这不是HTMX监听的内容

golang 的通用 map 功能

如何使用Promela建模语言对Golang RWLock进行建模

如何存储来自异步Goroutine的返回值列表?

为什么工具链指令在这种情况下没有效果?

在不耗尽资源的情况下处理S3文件下载

如何在Golang中覆盖404

go-jwt 令牌验证错误 - 令牌签名无效:密钥类型无效

Kperf 构建失败

使用golang sqlc中的引用参数

Go struct 匿名字段是公开的还是私有的?

从 eBPF LRU 哈希映射中错误驱逐的元素

Golang crypto/rand 线程安全吗?

golang yaml 马歇尔网址

如何将 npm 安装进度条通过管道传输到终端?

处理程序后访问 HTTP 请求上下文

GqlGen - 在字段解析器中访问查询输入参数

GOLANG 如何使用 http.FileServer 从模板目录加载某个 html 文件

如何断言类型是指向golang中接口的指针

Gorilla/Mux 和 Websocket 竞赛条件,这安全吗?