go-resty / resty

Simple HTTP and REST client library for Go
MIT License
9.89k stars 696 forks source link

Resty client global variable #737

Closed billypap1 closed 6 months ago

billypap1 commented 10 months ago

I use resty in my Golang app to call external APIs. Is it better to have it as a global variable or create it each time I need to call an external API?

My code bellow:

var RestyClient *resty.Client

func RestyClientSetup() {

    client := resty.New()
    client.SetTimeout(5 * time.Second)
    RestyClient = client
}

Will there be any issue with concurrent external API calls?

ahuigo commented 10 months ago

Global variables are not a good design and are prone to abuse. Imagine a scenario :

  1. moduleA wants to set SetTimeout(5 * time. Second)
  2. moduleB wants to SetTimeout(500 * time. Second)
  3. moduleC wants to SkipSSL(true)
  4. moduleD wants to SkipSSL(false)

This can easily create conflicts, and very difficult to manage and troubleshoot bugs.

If you want to use a global variable, you can define this global variable within your app, limited to your own app

jeevatkm commented 6 months ago

@ahuigo Thanks for responding to a comment.

@billypap1 It is recommended to create a resty client per destination Host with respective settings for the usage.

client1 := resty.New().SetBaseURL("http://localohost1")
....

client2 := resty.New().SetBaseURL("http://localohost2")
...