分析 GO 中的 Content Disposition 标头
时间:2024-02-29
浏览:320
作者:佚名
学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《分析 GO 中的 Content Disposition 标头》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!
我正在尝试从该 http writer 检索文件名以进行测试。 在我的服务器上:
func servefile(w http.responsewriter, r *http.request ) {
...
// file.name() is randomized with os.createtemp(dir, temp+"*"+ext) above
w.header().set("content-disposition", "attachment; filename="+file.name())
w.header().set("content-type", "application/octet-stream")
http.servefile(w, r, file.name()+".xyz") // serve file to user to download
...
}
*我将 .xyz 作为此演示的占位符
我正在使用 go 以编程方式测试此函数,我希望访问文件名以便能够将其保存在客户端代码中的变量中。
我已经看过这篇文章如何解析 content-disposition 标头以检索文件名属性? ,但我还没有让它发挥作用。我不知道客户端的文件名是什么,所以我不知道如何具体引用它。我知道我在服务器端的代码可以工作,因为当我(通过浏览器)向此端点/函数发送请求时,“下载”弹出窗口会显示文件下载进度以及文件名。
编辑**这是我调用它的客户端代码:
func TestGetFile(t *testing.T) {
...
cid := "some string"
// requestfile() creates, executes, and returns an httptest.ResponseRecorder to the requestFile endpoint
reqfileRespRecorder := requestfile()
// createTmpFile creates a new file out of the contents recieved in requestfile()
filePath := "/tmp/temp.xyz"
file := createTmpFile(reqfileRespRecorder , filePath)
// CreateWriter() - writes file contents to body of multipart.Writer
w, body := createWriter(file)
// Create request to postRecord endpoint
req, err := http.NewRequest("POST", "/PostRecord?CID="+cid, body)
check(err)
req.Header.Add("Content-Type", w.FormDataContentType())
// execute request to PostRecord endpoint. returns an httptest.ResponseRecorder
respRecorder := executeRequest(PostRecord, req)
disposition, params, err := mime.ParseMediaType(`Content-Disposition`)
...
}正确答案
基于@baytadarrell 的评论。我突然意识到我可以打印出答案。这帮助我意识到我正在尝试在错误的请求/响应之后找到内容处置。 The linked post 仍然没有帮助,但我的代码像这样工作:
func TestGetFile(t *testing.T) {
...
cid := "some string"
// requestfile() creates, executes, and returns an httptest.ResponseRecorder to the requestFile endpoint
reqfileRespRecorder := requestfile()
disp := reqfileRespRecorder.Header().Get("Content-Disposition")
line := strings.Split(disp, "=")
filename := line[1]
fmt.Println("filename: ", filename)
// createTmpFile creates a new file out of the contents recieved in requestfile()
filePath := "/tmp/temp.xyz"
file := createTmpFile(reqfileRespRecorder , filePath)
// CreateWriter() - writes file contents to body of multipart.Writer
w, body := createWriter(file)
...
}
他们的评论意识到我应该重新查看 httptest package documentation。在这里我找到了 header() 函数,并且我可以使用它通过 get() 查看标头。
这一行 reqfileresprecorder.header().get("content-disposition") 返回 attachment; filename=temp37bf73gd.xyz 并将文件名存储在我在 = 上拆分的变量中。
到这里,我们也就讲完了《分析 GO 中的 Content Disposition 标头》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
