Golang-发送API POST请求-参数不足错误



下面的代码试图发送一个POST API请求,其有效负载位于RequestDetails.FormData中。当我运行main.go函数时,我会得到以下错误。

go run main.go
# command-line-arguments
./main.go:53:17: not enough arguments in call to http.HandleFunc
./main.go:53:33: not enough arguments in call to reqDetails.Send
have ()
want (http.ResponseWriter, *http.Request)
./main.go:53:33: reqDetails.Send() used as value

代码如下所示。有人知道我在这里会做错什么吗?非常感谢你的帮助。

//main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
)
// RequestDetails contains input data for Send
type RequestDetails struct {
EndPoint string
FormType string
FormData map[string]string
}
// Send sends API POST request to an endpoint
func (rd RequestDetails) Send(w http.ResponseWriter, r *http.Request) {
json_data, err := json.Marshal(rd.FormData)
if err != nil {
log.Fatal(err)
}
resp, err := http.Post(rd.EndPoint, rd.FormType, bytes.NewBuffer(json_data))
if err != nil {
log.Fatal(err)
}
fmt.Println(resp)
}
func main() {
m := map[string]string{
"AuthParamOne":   "AP0000001",
"AuthParamTwo":   "AP0000002",
"AuthParamThree": "AP0000003",
}
reqDetails := RequestDetails{
EndPoint: "https://httpbin.org/post",
FormType: "application/json",
FormData: m,
}
http.HandleFunc(reqDetails.Send())
}

您必须在下面使用HandleFunc:

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

对于上面的代码,请遵循以下内容:

http.HandleFunc("/test",reqDetails.Send) //-> add reference instead of calling 'reqDetails.Send()'

参考:https://pkg.go.dev/net/http#HandleFunc

请投赞成票:(

在您的Send方法中,您不使用whttp。ResponseWriter,r*http.Request,所以你似乎不需要它们:

func (rd RequestDetails) Send() {...

同样在您的最后一行中,HandleFunc需要不同的参数,这在您的情况下也是不必要的。只需尝试运行发送方法:

reqDetails.Send()

整个main.go文件:

//main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
)
// RequestDetails contains input data for Send
type RequestDetails struct {
EndPoint string
FormType string
FormData map[string]string
}
// Send sends API POST request to an endpoint
func (rd RequestDetails) Send() {
json_data, err := json.Marshal(rd.FormData)
if err != nil {
log.Fatal(err)
}
resp, err := http.Post(rd.EndPoint, rd.FormType, bytes.NewBuffer(json_data))
if err != nil {
log.Fatal(err)
}
fmt.Println(resp)
}
func main() {
m := map[string]string{
"AuthParamOne":   "AP0000001",
"AuthParamTwo":   "AP0000002",
"AuthParamThree": "AP0000003",
}
reqDetails := RequestDetails{
EndPoint: "https://httpbin.org/post",
FormType: "application/json",
FormData: m,
}
reqDetails.Send()
}

如果你的代码喜欢这个

watcher := bufio.NewReader(os.Stdin)
input, _ := watcher.ReadString()    
fmt.Println(input)

你需要这个来读取行

old -> input, _ := watcher.ReadString()   
new -> input, _ := watcher.ReadString('n')   

最新更新