我想写一个小的助手函数来集中我的HTTP调用。来自Python的我仍然很难在Go中使用指针。
helper函数本质上采用带有调用信息(URL、方法和可选请求体(的struct
,并将响应体返回为[]byte
(目前为nil
(:
package main
import "net/http"
type httpParameters struct {
Url string
Method func(client http.Client, string2 string) (*http.Response, error)
Body []byte
}
func callHTTP(param httpParameters) (resp []byte, err error) {
return nil, nil
}
所附测试为
package main
import (
"net/http"
"testing"
)
func TestCallHTTP(t *testing.T) {
params := httpParameters{
Url: "https://postman-echo.com/get",
Method: http.Client.Get,
}
resp, err := callHTTP(params)
if err != nil {
t.Errorf("call to %v was not successful: %v", params.Url, err)
}
if resp != nil {
t.Errorf("GET call to %v returned something: %v, should be nil", params.Url, resp)
}
}
当试图运行时,我得到
.main_test.go:11:22: invalid method expression http.Client.Get (needs pointer receiver: (*http.Client).Get)
注意:类型声明中的Method func(client http.Client, string2 string) (*http.Response, error)
是一种反复尝试的方法——我最终把Get
定义中的内容放进去了。我不确定这种功能是否应该被称为
我应该如何寻址Get
方法才能在调用中传递它?
http.NewRequest(method, url, body)
将有助于实现同样的目标。
req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
Get
用指针接收器声明,即*http.Client
,不用值接收器声明,如不是http.Client
。
错误:
invalid method expression http.Client.Get (needs pointer receiver: (*http.Client).Get)
就是这么说的。并且,它甚至提供了方法表达式的适当形式,即(*http.Client).Get
。
这也意味着函数的签名必须相应地更改,即将client http.Client
更改为client *http.Client
。
type httpParameters struct {
Url string
Method func(*http.Client, string) (*http.Response, error)
Body []byte
}
func TestCallHTTP(t *testing.T) {
params := httpParameters{
Url: "https://postman-echo.com/get",
Method: (*http.Client).Get,
}
// ...
}
https://play.golang.org/p/83qgE4QeHx5