gpt4 book ai didi

go - 测试 Go http.Request.FormFile?

转载 作者:IT王子 更新时间:2023-10-29 00:40:06 25 4
gpt4 key购买 nike

尝试测试端点时如何设置 Request.FormFile?

部分代码:

func (a *EP) Endpoint(w http.ResponseWriter, r *http.Request) {
...

x, err := strconv.Atoi(r.FormValue("x"))
if err != nil {
a.ren.Text(w, http.StatusInternalServerError, err.Error())
return
}

f, fh, err := r.FormFile("y")
if err != nil {
a.ren.Text(w, http.StatusInternalServerError, err.Error())
return
}
defer f.Close()
...
}

我如何使用 httptest 库生成具有我可以在 FormFile 中获取的值的发布请求?

最佳答案

您不需要按照其他答案的建议模拟完整的 FormFile 结构。 mime/multipart 包实现了一个允许您创建 FormFile 的 Writer 类型。来自 the docs

CreateFormFile is a convenience wrapper around CreatePart. It createsa new form-data header with the provided field name and file name.

func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, error)

然后,您可以将此 io.Writer 传递给 httptest.NewRequest,它接受一个 reader 作为参数。

request := httptest.NewRequest("POST", "/", myReader)

为此,您可以将 FormFile 写入 io.ReaderWriter 缓冲区或使用 io.Pipe。这是一个使用管道的完整示例:

func TestUploadImage(t *testing.T) {
// Set up a pipe to avoid buffering
pr, pw := io.Pipe()
// This writer is going to transform
// what we pass to it to multipart form data
// and write it to our io.Pipe
writer := multipart.NewWriter(pw)

go func() {
defer writer.Close()
// We create the form data field 'fileupload'
// which returns another writer to write the actual file
part, err := writer.CreateFormFile("fileupload", "someimg.png")
if err != nil {
t.Error(err)
}

// https://yourbasic.org/golang/create-image/
img := createImage()

// Encode() takes an io.Writer.
// We pass the multipart field
// 'fileupload' that we defined
// earlier which, in turn, writes
// to our io.Pipe
err = png.Encode(part, img)
if err != nil {
t.Error(err)
}
}()

// We read from the pipe which receives data
// from the multipart writer, which, in turn,
// receives data from png.Encode().
// We have 3 chained writers!
request := httptest.NewRequest("POST", "/", pr)
request.Header.Add("Content-Type", writer.FormDataContentType())

response := httptest.NewRecorder()
handler := UploadFileHandler()
handler.ServeHTTP(response, request)

t.Log("It should respond with an HTTP status code of 200")
if response.Code != 200 {
t.Errorf("Expected %s, received %d", 200, response.Code)
}
t.Log("It should create a file named 'someimg.png' in uploads folder")
if _, err := os.Stat("./uploads/someimg.png"); os.IsNotExist(err) {
t.Error("Expected file ./uploads/someimg.png' to exist")
}
}

此函数利用 image 包动态生成文件,利用您可以将 io.Writer 传递给 png.Encode 。同样,您可以传递您的多部分 Writer 以生成 CSV 格式的字节(NewWriter 在包“encoding/csv”中),动态生成一个文件,而无需从您的文件系统中读取任何内容。

关于go - 测试 Go http.Request.FormFile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43904974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com