访问HTTP响应作为字符串在Go

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

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

283965 次浏览

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

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

在这篇文章中
(在将1.16—Q1 2021—ioutil弃用之后更新:ioutil.ReadAll() =>io.ReadAll()): < / p >

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回答中),这是一个转换(参见规范)。
看到“[]byte(string)有多贵?"(相反的问题,但同样的结论适用),其中睡眠提到:

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

索尼娅补充道:

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

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

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

正式文档 .

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

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

参考

  1. https://golang.org/doc/go1.16#ioutil
  2. https://stackoverflow.com/a/52076748/2876087 < a href = " https://stackoverflow.com/a/52076748/2876087 " > < / >