-
Notifications
You must be signed in to change notification settings - Fork 0
/
ginI18n.go
41 lines (33 loc) · 1.03 KB
/
ginI18n.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
package i18n
import (
"strings"
"github.com/gin-gonic/gin"
)
const localizerKey = "Localizer"
// Localizer options
type Options struct {
DefaultLang string // default language
SupportLangs string // list of supported languages (must include default language)
FilePath string // multilingual file directory
}
// Localizer middleware
func Localizer(opt *Options) gin.HandlerFunc {
defaultStr := strings.TrimSpace(opt.DefaultLang)
supportStr := strings.TrimSpace(opt.SupportLangs)
filePathStr := strings.TrimSpace(opt.FilePath)
if len(defaultStr) == 0 || len(supportStr) == 0 {
panic("bad defaultLang or supportLang")
}
l := newLocalize(defaultStr, supportStr, filePathStr)
return func(c *gin.Context) {
acceptLang := c.GetHeader("Accept-Language")
localizer := l.userLocalize(acceptLang)
c.Set(localizerKey, localizer)
c.Next()
}
}
// Get localizer message
func Msg(c *gin.Context, tag string, args ...interface{}) string {
localizer := c.MustGet(localizerKey).(*userLocalize)
return localizer.getMsg(tag, args...)
}