Begin dependency injection
This commit is contained in:
parent
23203e9ecd
commit
06776329bd
43
diego.go
Normal file
43
diego.go
Normal 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
22
diego_test.go
Normal 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)
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user