PaulSonOfLars / gotgbot

Autogenerated Go wrapper for the telegram API. Inspired by the python-telegram-bot library.
MIT License
509 stars 114 forks source link

Add support for middlewares in HTTP requests #46

Closed PaulSonOfLars closed 2 years ago

PaulSonOfLars commented 2 years ago

What

Move to using a bot interface instead of a bot struct. This requires quite a large refactor of the core "bot" concept to allow it to work that way, but hopefully all worth it.

There are two main reasons for the move to the interface:

1. Middlewares

The use of an interface means we can chain interfaces together to create middlewares. This is a big change, allowing us to drastically improve metrics, logs, and error handling.

Examples (Click to expand!) Adding the following code ``` type LoggingBot struct { gotgbot.BotClient } func (lb *LoggingBot) PostWithContext(ctx context.Context, method string, params map[string]string, data map[string]gotgbot.NamedReader, opts *gotgbot.RequestOpts) (json.RawMessage, error) { fmt.Println("Applying middleware to", method) return lb.BotClient.PostWithContext(ctx, method, params, data, opts) } func LogEverythingBot(b gotgbot.BotClient) gotgbot.BotClient { return &LoggingBot{b} } ``` Then, wrapping an existing bot instance with ``` b.UseMiddleware(LogEverythingBot) ``` Allows you to intercept every POST request directly. You can then modify fields, log errors, and add metrics to track all your requests.

2. Testing framework

This opens the door for a built-in testing framework with the type-safe guarantees that we have in the library now. All one would need is an interface of a BotClient mock! (Note: needs more exploring. Not ready yet!)

Impact

celestix commented 2 years ago

Greaaattttttt