Created
November 4, 2020 20:24
-
-
Save nskondratev/6a17c636bb3473a61ad972be303b89e2 to your computer and use it in GitHub Desktop.
HTTP-like handlers and middlewares for https://github.com/go-telegram-bot-api/telegram-bot-api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package bot | |
import ( | |
"context" | |
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" | |
) | |
type Bot interface { | |
// Here you can add any BotAPI methods you are going to use | |
Send(c tgbotapi.Chattable) (tgbotapi.Message, error) | |
GetFileDirectURL(fileID string) (string, error) | |
} | |
type Handler interface { | |
Handle(ctx context.Context, bot Bot, update *tgbotapi.Update) | |
} | |
type HandlerFunc func(ctx context.Context, bot Bot, update *tgbotapi.Update) | |
func (f HandlerFunc) Handle(ctx context.Context, bot Bot, update *tgbotapi.Update) { | |
f(ctx, bot, update) | |
} | |
type Middleware func(next Handler) Handler | |
type Chain struct { | |
middlewares []Middleware | |
} | |
func NewChain(middlewares ...Middleware) Chain { | |
return Chain{append(([]Middleware)(nil), middlewares...)} | |
} | |
func (c Chain) Then(h Handler) Handler { | |
for i := range c.middlewares { | |
h = c.middlewares[len(c.middlewares)-1-i](h) | |
} | |
return h | |
} | |
func (c Chain) ThenFunc(hf HandlerFunc) Handler { | |
return c.Then(hf) | |
} | |
func (c Chain) Append(middlewares ...Middleware) Chain { | |
newCons := make([]Middleware, 0, len(c.middlewares)+len(middlewares)) | |
newCons = append(newCons, c.middlewares...) | |
newCons = append(newCons, middlewares...) | |
return Chain{newCons} | |
} | |
func (c Chain) Extend(nc Chain) Chain { | |
return c.Append(nc.middlewares...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment