forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
41 lines (33 loc) · 1.08 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package meter
import (
"fmt"
"strings"
"github.com/evcc-io/evcc/api"
)
type meterRegistry map[string]func(map[string]interface{}) (api.Meter, error)
func (r meterRegistry) Add(name string, factory func(map[string]interface{}) (api.Meter, error)) {
if _, exists := r[name]; exists {
panic(fmt.Sprintf("cannot register duplicate meter type: %s", name))
}
r[name] = factory
}
func (r meterRegistry) Get(name string) (func(map[string]interface{}) (api.Meter, error), error) {
factory, exists := r[name]
if !exists {
return nil, fmt.Errorf("meter type not registered: %s", name)
}
return factory, nil
}
var registry meterRegistry = make(map[string]func(map[string]interface{}) (api.Meter, error))
// NewFromConfig creates meter from configuration
func NewFromConfig(typ string, other map[string]interface{}) (v api.Meter, err error) {
factory, err := registry.Get(strings.ToLower(typ))
if err == nil {
if v, err = factory(other); err != nil {
err = fmt.Errorf("cannot create meter '%s': %w", typ, err)
}
} else {
err = fmt.Errorf("invalid meter type: %s", typ)
}
return
}