Peter Kurfer
49e58ac2e4
- move to Gitlab - make code better testable - create app abstraction for server - cleanup
41 lines
733 B
Go
41 lines
733 B
Go
package defaulting
|
|
|
|
import (
|
|
"reflect"
|
|
)
|
|
|
|
type Defaulter func(instance interface{})
|
|
|
|
type Registry interface {
|
|
Register(t reflect.Type, defaulter ...Defaulter)
|
|
Apply(instance interface{})
|
|
}
|
|
|
|
func New() Registry {
|
|
return ®istry{
|
|
defaulters: make(map[reflect.Type][]Defaulter),
|
|
}
|
|
}
|
|
|
|
type registry struct {
|
|
defaulters map[reflect.Type][]Defaulter
|
|
}
|
|
|
|
func (r *registry) Register(t reflect.Type, defaulter ...Defaulter) {
|
|
var given []Defaulter
|
|
if r, ok := r.defaulters[t]; ok {
|
|
given = r
|
|
}
|
|
|
|
given = append(given, defaulter...)
|
|
|
|
r.defaulters[t] = given
|
|
}
|
|
|
|
func (r *registry) Apply(instance interface{}) {
|
|
if defs, ok := r.defaulters[reflect.TypeOf(instance)]; ok {
|
|
for _, def := range defs {
|
|
def(instance)
|
|
}
|
|
}
|
|
}
|