Skip to content

Commit

Permalink
feat: Context 添加部分与时区相关的方法
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed May 28, 2024
1 parent 1166727 commit 477c36e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
17 changes: 17 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,23 @@ func (ctx *Context) Route() types.Route { return ctx.route }
// Begin 当前对象的初始化时间
func (ctx *Context) Begin() time.Time { return ctx.begin }

// Location 当前用户的时区
//
// 默认情况下,该值与 [Server.Location] 相同。
func (ctx *Context) Location() *time.Location { return ctx.Begin().Location() }

// Now 相当于指定了时区的 [time.Now]
func (ctx *Context) Now() time.Time { return time.Now().In(ctx.Location()) }

// SetLocation 改变当前用户的时区
//
// 该操作也将同时改变 [Context.Begin] 的时区。
func (ctx *Context) SetLocation(l *time.Location) { ctx.begin = ctx.Begin().In(l) }

func (ctx *Context) ParseTime(layout, value string) (time.Time, error) {
return time.ParseInLocation(layout, value, ctx.Location())
}

// ID 当前请求的唯一 ID
//
// 一般源自客户端的 X-Request-ID 报头,如果不存在,则由 [Server.UniqueID] 生成。
Expand Down
11 changes: 11 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,14 @@ func TestContext_ClientIP(t *testing.T) {
ctx := newContext(a, nil, r)
a.NotNil(ctx).Equal(ctx.ClientIP(), r.RemoteAddr)
}

func TestContext_time(t *testing.T) {
a := assert.New(t, false)

r := httptest.NewRequest(http.MethodPost, "/path", bytes.NewBufferString("123"))
ctx := newContext(a, nil, r)

a.Equal(ctx.Location(), ctx.Server().Location()).
Equal(ctx.Now().Location(), ctx.Location()).
Equal(ctx.Begin().Location(), ctx.Location())
}
2 changes: 1 addition & 1 deletion filter/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ type Filter = func() (string, localeutil.Stringer)
// 当前函数的主要作用是将一个泛型函数转换为非泛型函数 [Filter]。
type Builder[T any] func(name string, value *T) Filter

// Rule 对类型 T 的验证规则
// Rule 类型 T 的验证规则
//
// 传递参数为字段名与需要验证的值;
// 返回字段名和错误信息,如果验证成功,则返回两个空值;
Expand Down

0 comments on commit 477c36e

Please sign in to comment.