gpt4 book ai didi

go - 如何从 http.Request 的响应中读取文件内容

转载 作者:行者123 更新时间:2023-12-01 22:38:57 25 4
gpt4 key购买 nike

我使用下面的代码向 http 服务器发送请求。

服务器发送包含这些 http header 的响应

Content-Disposition:[attachment;filename=somefilename.csv] 
Content-Type:[text/csv; charset=UTF-8]

我如何继续检索随响应附加的文件的内容?
baseUrl := "Some url that i call to fetch csv file"

client := http.Client{}

resp, _ := client.Get(baseUrl)
defer resp.Body.Close()

fmt.Println(resp)

// &{200 OK 200 HTTP/2.0 2 0 map[Content-Disposition:[attachment;filename=somefilename.csv] Content-Type:[text/csv; charset=UTF-8] Date:[Mon, 30 Sep 2019 09:54:08 GMT] Server:[Jetty(9.2.z-SNAPSHOT)] Vary:[Accept]] {0xc000530280} -1 [] false false map[] 0xc000156200 0xc0000c26e0}

最佳答案

您必须使用请求的正文。

baseUrl := "Some url that i call to fetch csv file"

client := http.Client{}

resp, _ := client.Get(baseUrl)
defer resp.Body.Close()
io.Copy(os.Stdout, resp.Body) // this line.

fmt.Println(resp)

如果您必须处理多部分表单数据 https://golang.org/pkg/net/http/#Request.FormFile

鉴于以下评论,

i see now after printing resp that there is a csv text but type is http.Response i have to deal with golang.org/pkg/encoding/csv/#Reader how to turn resp to string in order to be able reader to read it, or i miss something else ?



OP 必须了解 http 响应主体实现 io.Reader界面。
当 http 响应从服务器返回时,正文不会作为字节 slice 直接读入内存 []byte .

OP 还应注意 csv.Reader是一种对使用 io.Reader 的 CSV 编码内容进行解码的实现。 .在引擎盖下,它不会将文件的全部内容保存在内存中,它会读取解码一行所需的内容并继续进行。

由于 golang 实现的这两个重要属性,将响应正文阅读器连接到 csv 阅读器很容易和自然。

对于这个问题,什么是 io.Reader , OP 必须弄清楚它是能够通过 max len p block 读取字节流的任何东西。此接口(interface)的唯一方法的签名说明了这一点 Read([]byte) (int, error)
此接口(interface)的设计方式是最大限度地减少消耗的内存和分配。

引用链接
  • https://golang.org/pkg/encoding/csv/#Reader
  • https://golang.org/pkg/io/#Reader
  • https://golang.org/pkg/net/http/#Response

  • 说了这么多,最后的代码写得很简单,
    package main

    import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "net/http"
    )

    func main() {
    baseUrl := "https://geolite.maxmind.com/download/geoip/misc/region_codes.csv"

    client := http.Client{}

    resp, err := client.Get(baseUrl)
    if err != nil {
    log.Fatal(err)
    }
    defer resp.Body.Close()
    fmt.Println(resp)

    r := csv.NewReader(resp.Body)

    for {
    record, err := r.Read()
    if err == io.EOF {
    break
    }
    if err != nil {
    log.Fatal(err)
    }

    fmt.Println(record)
    }
    }

    关于go - 如何从 http.Request 的响应中读取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58165606/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com