How to get path and filename from postman request body using Go

huangapple go评论69阅读模式
英文:

How to get path and filename from postman request body using Go

问题

这个问题已经被问过了,但是没有解决我的问题。

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

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

我的Postman集合
How to get path and filename from postman request body using Go

我的代码

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

	// 配置端口
	fmt.Printf("Starting server at 8080 \n")
	http.ListenAndServe(":8080", router)
}

我试图打印带有路径的文件名,例如:/home/ramesh/videos/video.mp4

英文:

This question already asked but it is not solve my issue.

In my Go project am not able to print path and filename. It is showing some error like below:

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

My Postman collection
How to get path and filename from postman request body using Go

my code

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

>Am trying to print filename with path eg: /home/ramesh/videos/video.mp4

答案1

得分: 2

发送的请求中在Content-Type头部中缺少boundary参数。这个参数在multipart/form-data中是必需的,以使其正常工作。

在Postman中删除显式的Content-Type头部设置,并让Postman自动设置带有boundary参数的头部。

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

最后但并非最不重要的是,不要忽略错误

英文:

The sent request is missing the boundary parameter in the Content-Type header. This parameter is required for multipart/form-data to work properly.

In Postman remove the explicit Content-Type header setting and leave it to Postman to automatically set the header with the boundary parameter.

For more see: https://stackoverflow.com/a/16022213/965900 & https://stackoverflow.com/a/41435972/965900

Last but not least, do not ignore errors.

huangapple
  • 本文由 发表于 2021年10月13日 19:06:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/69554379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定