登录
首页 >  Golang >  Go问答

http.Get 函数的参数类型是什么?

来源:stackoverflow

时间:2024-02-23 11:45:24 400浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《http.Get 函数的参数类型是什么?》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我想编写一个小辅助函数来集中我的 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 方法才能在调用中传递它?


正确答案


Get 使用指针接收器声明,即 *http.client,并且使用值接收器声明,即 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

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>