【问题标题】:How to get path and filename from postman request body using Go如何使用 Go 从邮递员请求正文中获取路径和文件名
【发布时间】:2021-12-01 20:49:01
【问题描述】:

这个问题已经问过了,但它不能解决我的问题。

在我的Go 项目中无法打印路径和文件名。它显示如下错误:

2021/10/13 16:25:07 http: panic serving [::1]:60170: runtime error: invalid memory address or nil pointer dereference goroutine 6 [running]:

我的邮递员收藏

我的代码

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func encodeFfmpeg(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "multipart/form-data")
    _, header, _ := r.FormFile("video")
    fmt.Println(header.Filename)
}

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/encode", encodeFfmpeg).Methods("POST")

    // config port
    fmt.Printf("Starting server at 8080 \n")
    http.ListenAndServe(":8080", router)
}

我正在尝试使用路径打印文件名例如:/home/ramesh/videos/video.mp4

【问题讨论】:

  • FormFile 返回错误。在接触FormFile 返回的任何其他值之前检查错误。如果错误不是nil,那么header 很可能是nil,表达式header.Filename 恐慌。
  • 设置w.Header().Set("Content-Type", "multipart/form-data") 不会以任何方式修改r。除非您还使用有效负载进行响应,即编写该特定内容类型的响应正文,否则将其放在那里毫无意义。
  • @mkopriva: 我添加了`_, header, err := r.FormFile("video") if err != nil { panic(err) } ` 它显示了这个错误http: panic serving [::1]:60476: no multipart boundary param in Content-Type goroutine 6 [running]:跨度>
  • 表示Postman请求的Content-Type标头中的boundary参数缺失。 multipart/form-data 需要此参数才能正常工作。看到这个answer(边界在底部提到)。
  • 链接的答案、其关联的 cmets 以及其他答案也建议您不要设置 Content-Type,并让 Postman 自动设置它。第二个答案中的This 具有标题“如果在标题中失败”This 的标题为 "Works"

标签: forms go upload filenames


【解决方案1】:

发送的请求在Content-Type 标头中缺少boundary 参数。此参数是multipart/form-data 正常工作所必需的。

在 Postman 中删除显式的 Content-Type 标头设置,让 Postman 使用 boundary 参数自动设置标头。

更多信息请见:https://stackoverflow.com/a/16022213/965900 & https://stackoverflow.com/a/41435972/965900

最后但同样重要的是,不要忽略错误

【讨论】:

  • 感谢您提供的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 2020-03-11
相关资源
最近更新 更多