登录
首页 >  Golang >  Go问答

如何测试以文件夹作为输入的 HTTP 函数?

来源:stackoverflow

时间:2024-03-31 15:00:35 162浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《如何测试以文件夹作为输入的 HTTP 函数?》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我有一个 http 处理函数 (post),它允许用户从 web 浏览器应用程序上传文件夹。该文件夹作为文件夹中的文件数组从 javascript 代码传递,在后端(go api)上它被接受为 []*multipart.fileheader。我正在努力为这个函数编写 go 单元测试。如何传递文件夹作为测试函数的输入?我需要帮助以正确的格式创建 httprequest

我尝试使用/设置 fileheader 数组的值,但某些属性不允许导入。所以一定有一种我不知道的不同的方法来测试这个处理程序。

文件夹上传处理函数:

func folderupload(w http.responsewriter, r *http.request, p httprouter.params) { 
// some logic

files := r.multipartform.file["multiplefiles"] // files is of the type []*multipart.fileheader

// some logic to parse the file names to recreate the same tree structure on the server-side and store them as a folder

同一处理程序的单元测试函数:

func TestFolderUpload(t *testing.T) {
//     FolderPreCondition()
     request, err := http.NewRequest("POST", uri, body) //Q: HOW TO CREATE THE BODY ACCEPTABLE BY THE ABOVE HANDLER FUNC?
//     SOME ASSERTION LOGIC
}

解决方案


您应该编写您的文件来请求:

func newfileuploadrequest(url string, paramname, path string) (*http.request, error) {
file, err := os.open(path)

if err != nil {
    return nil, err
}

defer file.close()

body := new(bytes.buffer)

writer := multipart.newwriter(body)

part, err := writer.createformfile(paramname, filepath.base(path))

if err != nil {
    return nil, err
}

_, err = io.copy(part, file)

if err != nil {
    return nil, err
}

err = writer.close()
if err != nil {
    return nil, err
}
req, err := http.newrequest("post", url, body)

if err != nil {
    return nil, err
}

req.header.add("content-type", writer.formdatacontenttype())

return req, err

}

然后使用它:

req, err := newFileUploadRequest("http://localhost:1234/upload", "multiplefiles", path)

client := &http.Client{}

resp, err := client.Do(req)

这对我有用,希望对你有帮助)

终于介绍完啦!小伙伴们,这篇关于《如何测试以文件夹作为输入的 HTTP 函数?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>