英文:
Http POST leads to : Too many arguments to return
问题
这个错误意味着你的函数返回了一个字符串类型的参数,但是你的函数声明中没有指定返回值。要修复这个错误,你需要在函数声明中指定返回值类型为字符串,并在函数体中使用 return
语句返回字符串值。
修复后的代码如下所示:
func Postfunc(w http.ResponseWriter, rep *http.Request) string {
var jsonStr = []byte(`{"id":"10012"}`)
req, err := http.NewRequest("POST", "url", bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/Text")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyText, err := ioutil.ReadAll(resp.Body)
fmt.Println("responce Body:", string(bodyText))
p := string(bodyText)
return p
}
修复后的代码中,函数声明中指定了返回值类型为字符串 string
,并在函数体中使用 return
语句返回了字符串值 p
。
英文:
I'm having some troubles trying to execute a POST
using Golang
. With the code below
func Postfunc(w http.ResponseWriter , rep *http.Request) {
var jsonStr = []byte(`{"id":"10012"}`)
req, err := http.NewRequest("POST", "url", bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/Text")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
fmt.Println("responce Status:", resp.Status)
fmt.Println("responce Headers:", resp.Header)
defer resp.Body.Close()
bodyText, err := ioutil.ReadAll(resp.Body)
fmt.Println("responce Body:", string(bodyText))
p := string(bodyText)
return p
}
I get the following error:
too many arguments to return, have (string), want ()
What does this error mean? How can I fix this?
答案1
得分: 2
错误是完全正确的。你的函数签名是:
func Postfunc(w http.ResponseWriter , rep *http.Request)
它没有返回值。因此,你的最后一行:
return p
有太多的参数,实际上应该没有参数。如果你想要将文本写入 HTTP 响应中,可以使用 ResponseWriter
:
w.Write(bodyText)
英文:
The error is exactly right. Your function signature is:
func Postfunc(w http.ResponseWriter , rep *http.Request)
It has no return values. Therefore, your last line:
return p
Has too many arguments, which would be any arguments at all. If you want to write text to the HTTP response, use the ResponseWriter
:
w.Write(bodyText)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论