53 lines
1.5 KiB
Go
53 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"git.toowon.com/jimmy/go-common/requestctx"
|
|
"git.toowon.com/jimmy/go-common/tools"
|
|
)
|
|
|
|
// TimezoneHeaderName 时区请求头名称
|
|
const TimezoneHeaderName = "X-Timezone"
|
|
|
|
// GetTimezoneFromContext 从 context 中获取时区
|
|
func GetTimezoneFromContext(ctx context.Context) string {
|
|
return requestctx.Timezone(ctx)
|
|
}
|
|
|
|
// Timezone 时区处理中间件
|
|
func Timezone(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
timezone := r.Header.Get(TimezoneHeaderName)
|
|
if timezone == "" {
|
|
timezone = requestctx.DefaultTimezone
|
|
}
|
|
if _, err := tools.GetLocation(timezone); err != nil {
|
|
timezone = requestctx.DefaultTimezone
|
|
}
|
|
ctx := requestctx.WithTimezone(r.Context(), timezone)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// TimezoneWithDefault 时区处理中间件(可自定义默认时区)
|
|
func TimezoneWithDefault(defaultTimezone string) func(http.Handler) http.Handler {
|
|
if _, err := tools.GetLocation(defaultTimezone); err != nil {
|
|
defaultTimezone = requestctx.DefaultTimezone
|
|
}
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
timezone := r.Header.Get(TimezoneHeaderName)
|
|
if timezone == "" {
|
|
timezone = defaultTimezone
|
|
}
|
|
if _, err := tools.GetLocation(timezone); err != nil {
|
|
timezone = defaultTimezone
|
|
}
|
|
ctx := requestctx.WithTimezone(r.Context(), timezone)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|