【问题标题】:What is the type of http.Get, to use as a parameter in a function?http.Get 的类型是什么,用作函数中的参数?
【发布时间】:2021-08-02 12:36:28
【问题描述】:

我想编写一个小帮助函数来集中我的 HTTP 调用。来自 Python 的我仍然在为 Go 中指针的使用而苦恼。

辅助函数本质上接受带有调用信息(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.Request 结构,将其传递给 http.Client.Do 方法。文档中的示例(从顶部开始的第三个示例框):golang.org/pkg/net/http
  • 不太清楚Method 的意图是什么。 http.Client.Get 是一个带有接收器的方法,httpParameters.Method 另一方面是一个函数。它们不匹配。
  • @super:我想说“应该使用的方法是“GET””——这是为了避免为 GET 编写一个助手,为 POST 编写另一个助手等。 Oakad 的评论指出了正确的我认为的解决方案(至少更优雅)
  • "GET" 是一个字符串,所以 Method 字段应该只有 string 类型。请注意,http.Client.Get 只是 http.Client.Do 的一个方便的包装器。每当您必须灵活时,请使用 Do。

标签: go types


【解决方案1】:

Get 用指针接收器声明,即*http.Clientnot 用值接收器声明,即 not http.Client

错误:

invalid method expression http.Client.Get (needs pointer receiver: (*http.Client).Get)

就是这么说的。而且,它甚至提供了method expression 的正确形式,即(*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

【讨论】:

    【解决方案2】:

    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)
    // ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-26
      • 2023-04-03
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 2012-06-15
      相关资源
      最近更新 更多