Skip to content

Commit

Permalink
Add module
Browse files Browse the repository at this point in the history
  • Loading branch information
googollee committed Sep 17, 2023
1 parent 863b85f commit 3bf3245
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions module.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package espresso

import (
"context"
"fmt"
"reflect"
)

type moduleName string

type Module[T any] struct {
name moduleName
}

func DefineModule[T any]() Module[T] {
var t T
typ := reflect.TypeOf(t)
if typ.Kind() == reflect.Ptr {
panic("T should be a type, not a pointer.")
}

name := fmt.Sprintf("%T", t)

return Module[T]{
name: moduleName(name),
}
}

func (m Module[T]) With(ctx context.Context, moduleInstance *T) context.Context {
return context.WithValue(ctx, m.name, moduleInstance)
}

func (m Module[T]) Value(ctx context.Context) *T {
v := ctx.Value(m.name)
if v == nil {
return nil
}

ret, ok := v.(*T)
if !ok {
return nil
}

return ret
}

0 comments on commit 3bf3245

Please sign in to comment.