我想解析一个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正确地写入对文件的响应。

我已经检查了包装参考,但它并没有真正的帮助。


当前回答

你用来读取http正文响应的方法返回一个字节片:

func ReadAll(r io.Reader) ([]byte, error)

官方文档

可以将[]字节转换为字符串

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

其他回答

String (byteslice)将字节片转换为字符串,要知道这不仅是简单的类型转换,也是内存复制。

Go 1.16+更新(2021年2月)

弃用io/ioutil

代码应该是

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 u want to read the body many time
    // u need to restore 
    // reader := io.NopCloser(bytes.NewReader(bodyBytes))
    if err != nil {
        log.Fatal(err)
    }
    bodyString := string(bodyBytes)
    log.Info(bodyString)
}

参考

https://golang.org/doc/go1.16#ioutil https://stackoverflow.com/a/52076748/2876087

你用来读取http正文响应的方法返回一个字节片:

func ReadAll(r io.Reader) ([]byte, error)

官方文档

可以将[]字节转换为字符串

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

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

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

有点像在这个线程 (在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。

正如下面的评论(以及zzn的回答),这是一个转换(请参阅规范)。 参见“[]字节(字符串)有多贵?”(相反的问题,但同样的结论适用),其中ZZZZ提到:

有些转换与强制转换相同,如uint(myIntvar),它只是重新解释原地的位。

索尼娅补充道:

从字节切片中生成字符串,肯定涉及到在堆上分配字符串。不可变性迫使我们这样做。 有时,您可以通过尽可能多地使用[]字节进行优化,然后在末尾创建一个字符串。的字节。缓冲类型通常很有用。