From 5f938b2a7ab5f08ba4dfe164b26721f1b64ffd88 Mon Sep 17 00:00:00 2001 From: sigurniv Date: Wed, 18 Apr 2018 16:42:18 +0300 Subject: [PATCH] add option to pass custom http.Client to tb.NewBot() in case of proxying and other needs --- api.go | 4 ++-- bot.go | 10 ++++++++++ telebot_test.go | 17 +++++++++++++++-- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/api.go b/api.go index 5214bc40..a7303e7b 100644 --- a/api.go +++ b/api.go @@ -26,7 +26,7 @@ func (b *Bot) Raw(method string, payload interface{}) ([]byte, error) { return []byte{}, wrapSystem(err) } - resp, err := http.Post(url, "application/json", &buf) + resp, err := b.client.Post(url, "application/json", &buf) if err != nil { return []byte{}, errors.Wrap(err, "http.Post failed") } @@ -85,7 +85,7 @@ func (b *Bot) sendFiles( req.Header.Add("Content-Type", writer.FormDataContentType()) - resp, err := http.DefaultClient.Do(req) + resp, err := b.client.Do(req) if err != nil { return nil, errors.Wrap(err, "http.Post failed") } diff --git a/bot.go b/bot.go index 3fe051db..29f4b79f 100644 --- a/bot.go +++ b/bot.go @@ -20,6 +20,11 @@ func NewBot(pref Settings) (*Bot, error) { pref.Updates = 100 } + client := pref.Client + if client == nil { + client = http.DefaultClient + } + bot := &Bot{ Token: pref.Token, Updates: make(chan Update, pref.Updates), @@ -28,6 +33,7 @@ func NewBot(pref Settings) (*Bot, error) { handlers: make(map[string]interface{}), stop: make(chan struct{}), reporter: pref.Reporter, + client:client, } user, err := bot.getMe() @@ -49,6 +55,7 @@ type Bot struct { handlers map[string]interface{} reporter func(error) stop chan struct{} + client *http.Client } // Settings represents a utility struct for passing certain @@ -66,6 +73,9 @@ type Settings struct { // Reporter is a callback function that will get called // on any panics recovered from endpoint handlers. Reporter func(error) + + // HTTP Client used to make requests to telegram api + Client *http.Client } // Update object represents an incoming update. diff --git a/telebot_test.go b/telebot_test.go index 5078f49c..3bcd5c45 100644 --- a/telebot_test.go +++ b/telebot_test.go @@ -26,8 +26,21 @@ func TestBot(t *testing.T) { } } -func TestRecipient(_ *testing.T) { - bot := Bot{} +func TestRecipient(t *testing.T) { + token := os.Getenv("TELEBOT_SECRET") + if token == "" { + fmt.Println("ERROR: " + + "In order to test telebot functionality, you need to set up " + + "TELEBOT_SECRET environmental variable, which represents an API " + + "key to a Telegram bot.\n") + t.Fatal("Could't find TELEBOT_SECRET, aborting.") + } + + bot, err := NewBot(Settings{Token: token}) + if err != nil { + t.Fatal("couldn't create bot:", err) + } + bot.Send(&User{}, "") bot.Send(&Chat{}, "") }