英文:
sending struct to form field in golang
问题
我有一个结构体需要发送到一个API,这是一个POST请求。但输入是表单字段,而字段包含字符串、整数、浮点数和图像。
我尝试使用WriteField函数,但由于该函数只接受字符串作为参数,无法处理整数和浮点数。我该怎么办?这是我的结构体和代码片段:
c := finalObject{
name: Name,
ProfilePic:"/img/unknown.jpg",
owner:"Mr Hall",
latitude:26.5473828,
longitude:88.4249179,
opendays:"Monday-Friday",
openhours:"10am to 5pm",
catId:82,
address:address,
phone_number:2312312,
mobile_number:312312,
email:"dsdas@a.com",
}
url := "https://abcd.com/a"
fmt.Println("URL:>", url)
b, err := json.Marshal(c)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
var jsonStr = []byte(b)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Authorization", "AUTH_TOKEN")
req.Header.Set("enctype", "multipart/form-data")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
fmt.Printf("%#v", c);
英文:
I have a struct which I have to send to an api and it's a post request. But the input are form field. And the fields contains strings, integer, float and image.
I tried to use WriteField function but since this function only takes strings as parameters, I can't process integer and float. How do I do that. Here is my struct and the code snippet.
c := finalObject{
name: Name,
ProfilePic:"/img/unknown.jpg",
owner:"Mr Hall",
latitude:26.5473828,
longitude:88.4249179,
opendays:"Monday-Friday",
openhours:"10am to 5pm",
catId:82,
address:address,
phone_number:2312312,
mobile_number:312312,
email:"dsdas@a.com",
}
url := "https://abcd.com/a"
fmt.Println("URL:>", url)
b, err := json.Marshal(c)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
var jsonStr = []byte(b)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Authorization", "AUTH_TOKEN")
req.Header.Set("enctype", "multipart/form-data")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
fmt.Printf("%#v", c);
}
答案1
得分: 1
HTTP表单中的表单值只能作为字符串值发送。
如果你有自由决定表单键的权利,那么你可以将整个结构作为一个JSON编码的字符串添加到一个通用的"data"字段中,并发送请求。否则,你需要将结构值转换为字符串表示形式才能发送它们的请求。
英文:
The Form values in HTTP form are sent as string values only.
If you have the liberty of deciding the form keys as well then you can add the whole structure as a json-encoded string against a generic "data" field and send the request. Else, you'd have to convert the structure values to string representation to send them in request.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论