-
Notifications
You must be signed in to change notification settings - Fork 470
/
middleware.go
50 lines (42 loc) · 1.13 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package layout
import (
tele "gopkg.in/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 telebot middleware to make localization 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)
}
}
}
// Middleware wraps ordinary layout middleware with your default locale.
func (dlt *DefaultLayout) Middleware() tele.MiddlewareFunc {
return dlt.lt.Middleware(dlt.locale)
}