telebot/layout/middleware.go

51 lines
1.1 KiB
Go
Raw Normal View History

package layout
2020-09-25 20:17:49 +00:00
import (
tele "gopkg.in/tucnak/telebot.v3"
)
2020-11-04 20:50:09 +00:00
// LocaleFunc is the function used to fetch the locale of the recipient.
// Returned locale will be remembered and linked to the corresponding context.
2020-09-26 15:48:49 +00:00
type LocaleFunc func(tele.Recipient) string
2021-07-22 17:43:32 +00:00
// Middleware builds a telebot middleware to make localization work.
2020-11-04 20:50:09 +00:00
//
// Usage:
// b.Use(lt.Middleware("en", func(r tele.Recipient) string {
// loc, _ := db.UserLocale(r.Recipient())
// return loc
// }))
//
func (lt *Layout) Middleware(defaultLocale string, localeFunc ...LocaleFunc) tele.MiddlewareFunc {
var f LocaleFunc
if len(localeFunc) > 0 {
f = localeFunc[0]
}
return func(next tele.HandlerFunc) tele.HandlerFunc {
return func(c tele.Context) error {
locale := defaultLocale
if f != nil {
if l := f(c.Sender()); l != "" {
locale = l
}
}
2020-09-26 11:03:01 +00:00
lt.SetLocale(c, locale)
2020-10-01 13:23:44 +00:00
defer func() {
lt.mu.Lock()
delete(lt.ctxs, c)
lt.mu.Unlock()
}()
return next(c)
}
}
}
2021-07-22 17:43:32 +00:00
// Middleware wraps ordinary layout middleware with your default locale.
func (dlt *DefaultLayout) Middleware() tele.MiddlewareFunc {
return dlt.lt.Middleware(dlt.locale)
}