From 361dca5c851c8a8e116343dc68a0440bc607f0b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Sat, 5 Oct 2024 01:06:36 +0200 Subject: [PATCH] v0.0.521 ctxext --- README.md | 1 + ctxext/getter.go | 27 +++++++++++++++++++++++++++ goextVersion.go | 4 ++-- 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 ctxext/getter.go diff --git a/README.md b/README.md index c2c5253..c170018 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Potentially needs `export GOPRIVATE="gogs.mikescher.com"` | zipext | Mike | Utility for zip/gzip/tar etc | | reflectext | Mike | Utility for golang reflection | | fsext | Mike | Utility for filesytem access | +| ctxext | Mike | Utility for context.Context | | | | | | mongoext | Mike | Utility/Helper functions for mongodb (kinda abandoned) | | cursortoken | Mike | MongoDB cursortoken implementation | diff --git a/ctxext/getter.go b/ctxext/getter.go new file mode 100644 index 0000000..d7602d1 --- /dev/null +++ b/ctxext/getter.go @@ -0,0 +1,27 @@ +package ctxext + +import "context" + +func Value[T any](ctx context.Context, key any) (T, bool) { + v := ctx.Value(key) + if v == nil { + return *new(T), false + } + if tv, ok := v.(T); !ok { + return *new(T), false + } else { + return tv, true + } +} + +func ValueOrDefault[T any](ctx context.Context, key any, def T) T { + v := ctx.Value(key) + if v == nil { + return def + } + if tv, ok := v.(T); !ok { + return def + } else { + return tv + } +} diff --git a/goextVersion.go b/goextVersion.go index 489442d..7b03e4d 100644 --- a/goextVersion.go +++ b/goextVersion.go @@ -1,5 +1,5 @@ package goext -const GoextVersion = "0.0.520" +const GoextVersion = "0.0.521" -const GoextVersionTimestamp = "2024-10-05T01:02:25+0200" +const GoextVersionTimestamp = "2024-10-05T01:06:36+0200"