diff --git a/internal/web/metrics/prometheus.go b/internal/web/metrics/prometheus.go index b45bf25..ad26169 100644 --- a/internal/web/metrics/prometheus.go +++ b/internal/web/metrics/prometheus.go @@ -3,7 +3,7 @@ package metrics import ( "git.0x7f.app/WOJ/woj-server/internal/e" "git.0x7f.app/WOJ/woj-server/internal/misc/config" - "git.0x7f.app/WOJ/woj-server/internal/pkg/cast" + "git.0x7f.app/WOJ/woj-server/pkg/cast" "github.com/gin-gonic/gin" "github.com/prometheus/client_golang/prometheus" "github.com/samber/do" diff --git a/internal/pkg/cast/cast.go b/pkg/cast/cast.go similarity index 100% rename from internal/pkg/cast/cast.go rename to pkg/cast/cast.go diff --git a/pkg/utils/try.go b/pkg/utils/try.go new file mode 100644 index 0000000..2339520 --- /dev/null +++ b/pkg/utils/try.go @@ -0,0 +1,27 @@ +package utils + +type TryChain[T any, V comparable] struct { + result T + error V + success V +} + +func NewTry[T any, V comparable](success V) *TryChain[T, V] { + return &TryChain[T, V]{success: success} +} + +func (c *TryChain[T, V]) Try(callback func() (T, V)) *TryChain[T, V] { + c.result, c.error = callback() + return c +} + +func (c *TryChain[T, V]) Or(callback func() (T, V)) *TryChain[T, V] { + if c.error == c.success { + return c + } + return c.Try(callback) +} + +func (c *TryChain[T, V]) Done() (T, V) { + return c.result, c.error +} diff --git a/pkg/utils/try_test.go b/pkg/utils/try_test.go new file mode 100644 index 0000000..c844be2 --- /dev/null +++ b/pkg/utils/try_test.go @@ -0,0 +1,57 @@ +package utils + +import "testing" + +func TestTry(t *testing.T) { + t.Run("First Try", func(t *testing.T) { + val, err := NewTry[int, bool](true). + Try(func() (int, bool) { return 1, true }). + Or(func() (int, bool) { return 2, false }). + Or(func() (int, bool) { return 3, true }). + Or(func() (int, bool) { return 4, false }). + Done() + + if val != 1 && err != true { + t.Error("Try failed") + } + }) + + t.Run("Middle Or", func(t *testing.T) { + val, err := NewTry[int, bool](true). + Try(func() (int, bool) { return 1, false }). + Or(func() (int, bool) { return 2, false }). + Or(func() (int, bool) { return 3, true }). + Or(func() (int, bool) { return 4, false }). + Done() + + if val != 3 && err != true { + t.Error("Try failed") + } + }) + + t.Run("Last Or", func(t *testing.T) { + val, err := NewTry[int, bool](true). + Try(func() (int, bool) { return 1, false }). + Or(func() (int, bool) { return 2, false }). + Or(func() (int, bool) { return 3, false }). + Or(func() (int, bool) { return 4, true }). + Done() + + if val != 4 && err != true { + t.Error("Try failed") + } + }) + + t.Run("Nothing", func(t *testing.T) { + val, err := NewTry[int, bool](true). + Try(func() (int, bool) { return 1, false }). + Or(func() (int, bool) { return 2, false }). + Or(func() (int, bool) { return 3, false }). + Or(func() (int, bool) { return 4, false }). + Done() + + if val != 4 && err != false { + t.Error("Try failed") + } + }) +}