Begin dependency injection

This commit is contained in:
Robin 2024-10-23 21:59:11 +02:00
parent 23203e9ecd
commit 06776329bd
3 changed files with 68 additions and 0 deletions

43
diego.go Normal file
View File

@ -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() {
}

22
diego_test.go Normal file
View File

@ -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)
}
}

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module robaertschi.xyz/diego
go 1.23.2