英文:
HTTP POST in GO Lang throws error
问题
我正在尝试使用GO语言进行POST请求。API URL期望在请求体中传递一个用户名和密码字段。然而,我一直收到以下错误信息:
我不确定我在这里做错了什么?
错误信息:
url.Values未定义(类型string没有Values字段或方法)
GO函数:
func makeHttpPostReq(url string, username string, password string){
client := http.Client{}
req, err := http.NewRequest("POST", url, url.Values{"username": {username}, "password": {password}})
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
fmt.Println("无法连接到服务器。")
} else {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("body=", string(body))
}
}
英文:
I am trying to make a Post request using in GO Lang. The API URL is expecting a username and password field to be passed to it in body. However I keep getting the below error ?
I am not sure what am i doing wrong here ?
Error
url.Values undefined (type string has no field or method Values)
Go Function
func makeHttpPostReq(url string, username string, password string){
client := http.Client{}
req, err := http.NewRequest("POST", url, url.Values{"username": {username}, "password": {password}})
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Unable to reach the server.")
} else {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("body=", string(body))
}
}
答案1
得分: 4
makeHttpPostReq
的参数表明url
是一个字符串,但你将其作为结构体url.Values
来处理,因此出现了错误
没有字段或方法
英文:
The argument to makeHttpPostReq
states url is a string but you are treating it as a struct url.Values
, thus the error
> has no field or method
答案2
得分: 2
你正在重复使用url
这个词。
在你的情况下,url
被解析为一个字符串,而不是net/url
。
英文:
You are reusing the url
word.
url is in your case resolving to url as a string not a net/url
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论