当前位置: > > > > 如何在 Go 中发送带有图像和一些参数的 http post 请求?
如何在 Go 中发送带有图像和一些参数的 http post 请求?
来源:stackoverflow
2024-04-25 10:54:25
0浏览
收藏
有志者,事竟成!如果你在学习Golang,那么本文《如何在 Go 中发送带有图像和一些参数的 http post 请求?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
我试图在表单数据中使用图像和参数发出http post请求,但是当我添加图像时,我的参数丢失了。
testproduct := &product{
name: "testproductname",
imageextension: "png",
}
var b bytes.buffer
multipartwriter := multipart.newwriter(&b)
multipartwriter.createformfile("image", "../test.png")
multipartwriter.close()
form = url.values{}
form.add("name", testproduct.name)
form.add("image_extension", testproduct.imageextension)
req, _ := http.newrequest(http.methodpost, "api/v1/admin/products/", &b)
req.postform = form
req.header.add("authorization", "bearer "+loginresponse.token)
req.header.set("content-type", multipartwriter.formdatacontenttype())
recorder := httptest.newrecorder()
router.servehttp(recorder, req)
但是当请求处理时,参数没有绑定: https://i.stack.imgur.com/wqasc.png
这是产品结构:
type Product struct {
ID string `form:"id" json:"id"`
Name string `form:"name" json:"name"`
Price int64 `form:"price" json:"price"`
ImageExtension string `form:"image_extension" json:"image_extension"`
}
解决方案
testProduct := &Product{
Name: "TestProductName",
ImageExtension: "png",
}
pr, pw := io.Pipe()
form := multipart.NewWriter(pw)
go func() {
defer pw.Close()
err := form.WriteField("name", testProduct.Name)
if err != nil {
return
}
err = form.WriteField("image_extension", testProduct.ImageExtension)
file, err := os.Open("a.png") // path to image file
if err != nil {
return
}
w, err := form.CreateFormFile("image", "sampleImageFileName.png")
if err != nil {
return
}
_, err = io.Copy(w, file)
if err != nil {
return
}
form.Close()
}()
r, err := http.NewRequest(http.MethodPost, "api/v1/admin/products/", pr)
if err != nil {
return
}
r.Header.Set("Content-Type", form.FormDataContentType())
本篇关于《如何在 Go 中发送带有图像和一些参数的 http post 请求?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注米云公众号!
