如何在 Go 中制作自定义 http 客户端?

How to make a custom http client in Go?

我想创建一个自定义的 http 客户端,这样我就可以尽可能多地重复使用它。 但是,我认为 Go 已经抽象了代码背后发生的一些过程。 我知道要有一个 get 请求,必须创建一个客户端。

客户端是在哪里创建的,如何自定义或替换为我自己的?

package main

import (
    "fmt"
    "github.com/njasm/gosoundcloud"
)

 s, err = gosoundcloud.NewSoundcloudApi("Client_Id", "Client_Secret", nil)


func main() {
    if err = s.PasswordCredentialsToken("email@example.com", "password"); err != nil {
    fmt.Println(err)
    os.Exit(1)
}
    member, err := s.GetUser(uint64(1))
    if err != nil {
               panic(err)
     }
    fmt.Println(member.Followers)
}

这里是 soundcloud 包装器的引用:

func NewSoundcloudApi(c string, cs string, callback *string) (*SoundcloudApi, error)

func (s *SoundcloudApi) PasswordCredentialsToken(u string, p string) error

func (s *SoundcloudApi) GetUser(id uint64) (*User, error)

使用 Golang,您可以轻松创建客户端并将其用于请求:

client := &http.Client{
    CheckRedirect: redirectPolicyFunc,
}

resp, err := client.Get("http://example.com")

See the http documentation

但在您的情况下,根据您使用的 gosoundcloud 包,http.Client 是在调用时创建的:

s.PasswordCredentialsToken("email@example.com", "password");

创建的客户端嵌入到 "SoundcloudApi" 结构中(您代码中的 "s"),并且是一个私有字段。因此,您无法访问它。

不管怎样,它似乎在你要求 "s" 做某事的任何时候使用(例如,当调用 s.User 时),所以它似乎可以满足你的要求。