Skip to content

Commit

Permalink
feat. UseValue
Browse files Browse the repository at this point in the history
  • Loading branch information
PotatoCloud committed Nov 21, 2023
1 parent 8b7cddf commit 6c11b6a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
11 changes: 11 additions & 0 deletions tool.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,14 @@ func Use(ctx context.Context) (*Context, bool) {
c, ok := ctx.(*Context)
return c, ok
}

func UseValue[T any](ctx *Context, key string) (T, bool) {
val, found := ctx.Get(key)
if !found {
var zero T
return zero, false
}

av, ok := val.(T)
return av, ok
}
19 changes: 19 additions & 0 deletions tool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,22 @@ func ExampleRegisterHandler() {
return nil
})
}

func ExampleUseValue() {
c, ok := pkgCtl.Use(ctx)
if !ok {
return
}

c.Set("K", "V")

catch, ok := pkgCtl.UseValue[string](c, "K")
if !ok {
return
}

if catch != "V" {
// fail
}
// success
}

0 comments on commit 6c11b6a

Please sign in to comment.