This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
langman.go
82 lines (68 loc) · 1.67 KB
/
langman.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package langman
import (
"net/http"
"strings"
"github.com/aofei/air"
)
// GasConfig is a set of configurations for the `Gas`.
type GasConfig struct {
// ParamName is the name of the param used to cover the original
// Accept-Language header.
//
// Default: "accept-language"
ParamName string
// CookieName is the name of the cookie used to cover the original
// Accept-Language header.
//
// Default: "accept-language"
CookieName string
// CookieMaxAge is the max-age of the cookie used to cover the original
// Accept-Language header.
//
// Default: 0
CookieMaxAge int
Skippable func(*air.Request, *air.Response) bool
}
// Gas returns an `air.Gas` that is used to manage the Accept-Language header
// based on the gc.
func Gas(gc GasConfig) air.Gas {
paramName := gc.ParamName
if paramName == "" {
paramName = "accept-language"
}
cookieName := gc.CookieName
if cookieName == "" {
cookieName = "accept-language"
}
return func(next air.Handler) air.Handler {
return func(req *air.Request, res *air.Response) error {
if gc.Skippable != nil && gc.Skippable(req, res) {
return next(req, res)
}
param := req.Param(paramName)
if param == nil {
cookie := req.Cookie(cookieName)
if cookie != nil {
req.Header.Set(
"Accept-Language",
cookie.Value,
)
}
return next(req, res)
}
als := make([]string, len(param.Values))
for i, al := range param.Values {
als[i] = al.String()
}
al := strings.Join(als, ",")
req.Header.Set("Accept-Language", al)
res.SetCookie(&http.Cookie{
Name: cookieName,
Value: al,
Path: "/",
MaxAge: gc.CookieMaxAge,
})
return next(req, res)
}
}
}