Http POST导致:返回的参数过多

huangapple go评论140阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2017年5月24日 04:12:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/44144181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定