From 06776329bd2e347f386a0f823a74af4ea381d758 Mon Sep 17 00:00:00 2001 From: Robin Date: Wed, 23 Oct 2024 21:59:11 +0200 Subject: [PATCH] Begin dependency injection --- diego.go | 43 +++++++++++++++++++++++++++++++++++++++++++ diego_test.go | 22 ++++++++++++++++++++++ go.mod | 3 +++ 3 files changed, 68 insertions(+) create mode 100644 diego.go create mode 100644 diego_test.go create mode 100644 go.mod diff --git a/diego.go b/diego.go new file mode 100644 index 0000000..6c18486 --- /dev/null +++ b/diego.go @@ -0,0 +1,43 @@ +package diego + +import ( + "fmt" + "net/http" +) + +type Router struct { + mux http.ServeMux +} + +type InjectionContext struct{} + +type InjectionFunction[T any] func(InjectionContext) T + +type InjectionToken[T any] struct { + Name string + InjectionFunc InjectionFunction[T] +} + +var injectionTokens map[string]any = make(map[string]any) + +func Inject[T any](token InjectionToken[T]) T { + var value = injectionTokens[token.Name] + + if value == nil { + value = token.InjectionFunc(InjectionContext{}) + injectionTokens[token.Name] = value + } + + var injection, ok = value.(T) + + if !ok { + panic(fmt.Sprintf("FATAL ERROR: Tried to inject a value with the wrong type, expected = %T, got = %T", *new(T), value)) + } + return injection + +} + +func Test() {} + +func (r *Router) Start() { +} diff --git a/diego_test.go b/diego_test.go new file mode 100644 index 0000000..5877ba0 --- /dev/null +++ b/diego_test.go @@ -0,0 +1,22 @@ +package diego + +import "testing" + +const testString = "hello" + +func GetBasicString(ctx InjectionContext) string { + return testString +} + +var BasicStringToken InjectionToken[string] = InjectionToken[string]{ + "BASIC_STRING", + GetBasicString, +} + +func TestDependencyInjection(t *testing.T) { + value := Inject(BasicStringToken) + + if value != testString { + t.Errorf("Could not inject basic string token, expected = %s(%T), got = %s(%T)", testString, testString, value, value) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e69af28 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module robaertschi.xyz/diego + +go 1.23.2