Juanvulcano
Juanvulcano

Reputation: 1396

How to make a custom http client in Go?

I want to create a custom http Client so I can reuse it as many times as possible. However, I think Go has abstracted some of the processes that happen behind the code. I understand that to have a get request a client must have been created.

Where is the client created and how can I customize it or replace it with my own?

package main

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

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


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

Here are the references of the soundcloud wrapper:

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)

Upvotes: 4

Views: 4049

Answers (1)

jnmoal
jnmoal

Reputation: 1015

With Golang, you can easily create a client and use it for a request:

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

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

See the http documentation

But in your case, according to the gosoundcloud package you are using, the http.Client is created when calling:

s.PasswordCredentialsToken("[email protected]", "password");

The created client is embedded into the "SoundcloudApi" struct (the "s" in your code), and is a private field. Thus, you can't access it.

Anyway it seems to be used anytime you ask "s" to do something (when calling s.User for example), so it seems to do what you are asking for.

Upvotes: 3

Related Questions