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.
ntool-biz/core/i18n/http.go

64 lines
1.5 KiB
Go

package i18n
import (
"context"
"net/http"
)
type HttpKeyConfig struct {
ParamKey string `json:",optional,default=lang"` // 参数中的语言Key
HeaderKey string `json:",optional,default=X-LANG"` // Header中的语言Key
}
var (
paramKey = "lang"
headerKey = "X-LANG"
)
// WithHttpConfig 基于配置文件设置Keys
func WithHttpConfig(config HttpKeyConfig) {
WithHttpParamKey(config.ParamKey)
WithHttpHeaderKey(config.HeaderKey)
}
// WithHttpParamKey 设置参数key
func WithHttpParamKey(key string) {
paramKey = key
}
// WithHttpHeaderKey 设置头Key
func WithHttpHeaderKey(key string) {
headerKey = key
}
// WithRequest 包装 http.Request, 接受客户端传递的lang并存入其 context 中
func WithRequest(r *http.Request) *http.Request {
paramLang := r.FormValue(paramKey)
headerLang := r.Header.Get(headerKey)
acceptLanguage := r.Header.Get(KeyAcceptLanguage)
ConfigLanguages(acceptLanguage, paramLang, headerLang)
// 参数中的lang优先级大于header中
lang := headerLang
if len(paramLang) != 0 {
lang = paramLang
}
ctx := r.Context()
if len(lang) > 0 {
ctx = context.WithValue(ctx, KeyLang, lang)
}
return r.WithContext(ctx)
}
// WithI18nMiddleware i18n中间件
func WithI18nMiddleware() func(next http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
req := WithRequest(request)
next.ServeHTTP(writer, req)
}
}
}