Skip to content

Commit

Permalink
refactor(timezone): Refactoring timezone
Browse files Browse the repository at this point in the history
Signed-off-by: Flc゛ <four_leaf_clover@foxmail.com>
  • Loading branch information
flc1125 committed Mar 12, 2024
1 parent 18f206a commit 9d9c511
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 deletions.
17 changes: 17 additions & 0 deletions timezone/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package timezone

import (
"context"
"time"
)

type contextKey struct{}

func NewContext(ctx context.Context, local *time.Location) context.Context {
return context.WithValue(ctx, contextKey{}, local)
}

func FromContext(ctx context.Context) (*time.Location, bool) {
local, ok := ctx.Value(contextKey{}).(*time.Location)
return local, ok
}
8 changes: 4 additions & 4 deletions timezone/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func Local(name string) Option {
}
}

func Provider(opts ...Option) func(ctx context.Context) error {
func Provider(opts ...Option) func(ctx context.Context) (context.Context, error) {
op := options{
local: "UTC",
}
Expand All @@ -26,14 +26,14 @@ func Provider(opts ...Option) func(ctx context.Context) error {
opt(&op)
}

return func(context.Context) error {
return func(ctx context.Context) (context.Context, error) {
location, err := time.LoadLocation(op.local)
if err != nil {
return err
return ctx, err
}

time.Local = location

return nil
return NewContext(ctx, location), nil
}
}
15 changes: 12 additions & 3 deletions timezone/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,22 @@ import (
func TestTimezone(t *testing.T) {
// before
assert.Equal(t, "Local", time.Local.String())
assert.NoError(t, Provider()(context.Background()))
ctx1, err1 := Provider()(context.Background())
assert.NoError(t, err1)
assert.Equal(t, "UTC", time.Local.String())
local1, ok1 := FromContext(ctx1)
assert.True(t, ok1)
assert.Equal(t, "UTC", local1.String())

// after
assert.NoError(t, Provider(Local("Asia/Shanghai"))(context.Background()))
ctx2, err2 := Provider(Local("Asia/Shanghai"))(context.Background())
assert.NoError(t, err2)
assert.Equal(t, "Asia/Shanghai", time.Local.String())
local2, ok2 := FromContext(ctx2)
assert.True(t, ok2)
assert.Equal(t, "Asia/Shanghai", local2.String())

// err
assert.Error(t, Provider(Local("Asia/Beijing"))(context.Background()))
_, err3 := Provider(Local("Asia/Beijing"))(context.Background())
assert.Error(t, err3)
}

0 comments on commit 9d9c511

Please sign in to comment.