GO服务器将标题Content-Type设置为Multipart/Form-Data

router.HandleFunc("/certificates", serveFilesHandler).Methods("GET")

func serveFilesHandler(w http.ResponseWriter, r *http.Request) {

    currentDir, err := os.Getwd()
    if err != nil {
        log.Fatal("Can not find the current directory: ", err)
    }
    pathToCertifs := "../certificates"

    // Create a multipart writer for the response
    multipartWriter := multipart.NewWriter(w)

    files := []string{"client.key", "server.key", "rootCA.key"}

    for _, filename := range files {
        filePath := filepath.Join(currentDir, pathToCertifs, filename)

        fmt.Println("see the filePath: ", filePath)

        // Open the file
        file, err := os.Open(filePath)
        if err != nil {}
        defer file.Close()

        // Create a new form file part
        part, err := multipartWriter.CreateFormFile("files", filename)
        if err != nil {}

        // Copy the file content to the part
        _, err = io.Copy(part, file)
        if err != nil {}
    }

    // Set the content type for the response
    w.Header().Set("Content-Type", multipartWriter.FormDataContentType())
    fmt.Println("Content-Type set to:", w.Header().Get("Content-Type"))
    // printout Content-Type set to: multipart/form-data; boundary=7b326

    // Close the multipart writer
    multipartWriter.Close()
}

但在客户方面,

Expected multipart response, but received: text/plain; charset=utf-8

然而,有效载荷在主体中

body, err := ioutil.ReadAll(resp.Body)
    if err != nil {}
Content-Type: text/plain; charset=utf-8
Response Body:
--aee406774ba6a054d52e39a3cdb72f42d32bd30828adbfb1982d278cab56
Content-Disposition: form-data; name="files"; filename="client.key"
Content-Type: application/octet-stream

-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDNg4ZaTLC/GdLK
xzFDIyPlYyKs/hUXpPkZAQk+3gnvmBaDuMNq2jd2nQoQohmk1zIuD8oj9se5L+3P

但我不能按部分获取它,因为内容类型不是多部分/表单数据,所以这不起作用

multipartReader := multipart.NewReader(resp.Body, boundaryFromContentType(contentType))

    // Read each part
    for {
        part, err := multipartReader.NextPart()
        if err != nil {
            break
        }
        defer part.Close()
......

我错过了什么,谢谢?

ps:更多的细节要求张贴这个问题,我觉得这是很清楚,所以我添加这一行,它可能会工作后.

推荐答案

在将任何内容写入响应正文之前,必须设置HTTP响应头.一旦提交了标头(当您向响应正文中写入内容时),就不能设置或更改标头.

创建多部分编写器以及所有部分和内容,然后设置响应头,然后只关闭多部分编写器.结束只是完成多部分消息和写入尾部边界,但它的许多内容可能已经编写和提交.

在向多部分编写器添加/写入任何内容之前移动设置标题(S):

// Create a multipart writer for the response
multipartWriter := multipart.NewWriter(w)

w.Header().Set("Content-Type", multipartWriter.FormDataContentType())

// Now proceed to add files...

Go相关问答推荐

你能帮我优化一个golang代码关于函数CrossPointTwoRect

如何预编译Golang标准库?

如何使用GO GIN从Auth0 JWT内标识检索权限

正确使用pgtype的方法

go测试10m后如何避免超时

如何将任何类型的数据值传递到 Golang 中的 GRPC Protobuf struct ?

同一文件上的多个 Arrow CSV 阅读器返回 null

使用 LINQ 对内部数组进行排序

上传图片失败,出现错误dial tcp: lookup api.cloudinary.com: no such host

Apache Beam 左加入 Go

如何为导入的嵌入式 struct 文字提供值?

Wire google Inject with multi return from provider 函数

速率限制特定端点

为什么在单独的 go routine 中需要 wg.Wait() 和 close() ?

在 Golang 中,如何将接口作为泛型类型与 nil 进行比较?

Golang Getrlimit 返回与 ulimit 不同的值

切片到数组指针的转换

使用反射在 struct 内迭代切片 struct

如何正确为 Go 中的值设置多种类型?

正确编码 JWT