You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
telebot/layout/middleware.go

47 lines
994 B
Go

package layout
import (
tele "gopkg.in/tucnak/telebot.v3"
)
// LocaleFunc is the function used to fetch the locale of the recipient.
// Returned locale will be remembered and linked to the corresponding context.
type LocaleFunc func(tele.Recipient) string
// Middleware builds a global middleware to make internationalisation work.
//
// 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
}
}
lt.SetLocale(c, locale)
defer func() {
lt.mu.Lock()
delete(lt.ctxs, c)
lt.mu.Unlock()
}()
return next(c)
}
}
}