英文:
Unit testing a HTTP handler that returns a stream of multiple files
问题
HTTP处理程序
我有一个像这样的HTTP处理程序:
func RouteHandler(c echo.Context) error {
outs := make([]io.Reader, 5)
for i := range outs {
outs[i] = // ...来自逻辑。
}
return c.Stream(http.StatusOK, "application/binary", io.MultiReader(outs...))
}
单元测试
我打算为HTTP处理程序编写一个单元测试,并调查返回的多个文件流。
我为我的单元测试准备了以下辅助类型和函数:
type Handler func(echo.Context) error
// 发送请求到处理程序。获取响应体。
func Send(req *http.Request, handler Handler) ([]byte, error) {
w := httptest.NewRecorder()
e := echo.New()
c := e.NewContext(req, w)
// 调用处理程序。
err := handler(c)
if err != nil {
return nil, err
}
res := w.Result()
defer res.Body.Close()
return ioutil.ReadAll(res.Body)
}
然后,我使用上述类型和函数从我的单元测试中向我的HTTP处理程序发送请求:
// 从我的单元测试中:
// 初始化请求...
var data []byte
data, err := Send(request, RouteHandler)
// 如何分离这里返回的多个文件?
// 如何处理HTTP处理程序返回的数据?
处理返回的文件流
我该如何分离HTTP处理程序返回的多个文件?我该如何处理HTTP处理程序返回的数据流?
英文:
HTTP handler
I have a HTTP handler like this:
func RouteHandler(c echo.Context) error {
outs := make([]io.Reader, 5)
for i := range outs {
outs[i] = // ... comes from a logic.
}
return c.Stream(http.StatusOK, "application/binary", io.MultiReader(outs...))
}
Unit test
I intend to write a unit test for HTTP handler and investigate the returned stream of multiple files.
I have these helper type and function for my unit test:
type Handler func(echo.Context) error
// Send request to a handler. Get back response body.
func Send(req *http.Request, handler Handler) ([]byte, error) {
w := httptest.NewRecorder()
e := echo.New()
c := e.NewContext(req, w)
// Call the handler.
err := handler(c)
if err != nil {
return nil, err
}
res := w.Result()
defer res.Body.Close()
return ioutil.ReadAll(res.Body)
}
Then, I use the above type and function to send a request to my HTTP handler from within my unit test:
// From within my unit test:
// Initialize request...
var data []byte
data, err := Send(request, RouteHandler)
// How to separate the multiple files returned here?
// How to work with the returned data?
Work with returned stream of files
How can I separate multiple files returned by the HTTP handler? How can I work with the stream of data returned by HTTP handler?
答案1
得分: 0
实际上,@CeriseLimón评论中提到的选项已经被实现并被前端使用。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论