From 6c11b6a482e85ad728fc5a2a5b9d18e79f2b4688 Mon Sep 17 00:00:00 2001 From: PotatoCloud <60210021+PotatoCloud@users.noreply.github.com> Date: Tue, 21 Nov 2023 09:19:38 +0800 Subject: [PATCH] feat. UseValue --- tool.go | 11 +++++++++++ tool_test.go | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/tool.go b/tool.go index b0525f4..849bb54 100644 --- a/tool.go +++ b/tool.go @@ -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 +} diff --git a/tool_test.go b/tool_test.go index a64f2ae..8fd6bae 100644 --- a/tool_test.go +++ b/tool_test.go @@ -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 +}