-
Notifications
You must be signed in to change notification settings - Fork 1
/
configuration.go
54 lines (46 loc) · 1.27 KB
/
configuration.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
42
43
44
45
46
47
48
49
50
51
52
53
54
package unipitt
import (
"io/ioutil"
"log"
yaml "gopkg.in/yaml.v2"
)
// Configuration represents the topic name for the MQTT message for a given instance name
type Configuration struct {
Topics map[string]string
}
// Topic gets a topic (value) for a given name (key). Return the name itself as fallback
func (c *Configuration) Topic(name string) string {
if value, ok := c.Topics[name]; ok {
return value
}
return name
}
// reverseTopics construct reverse mapping of topics
func (c *Configuration) reverseTopics() map[string]string {
r := make(map[string]string)
for key, value := range c.Topics {
r[value] = key
}
return r
}
// Name reverse mapping of topic for given name. In case nothing is found, just return the topic itself, hoping there's a mapped instance for it
func (c *Configuration) Name(topic string) string {
if name, ok := c.reverseTopics()[topic]; ok {
return name
}
return topic
}
// configFromFile reads a configuration from a yaml file
func configFromFile(configFile string) (c Configuration, err error) {
f, err := ioutil.ReadFile(configFile)
if err != nil {
log.Printf("Error reading config file: %s\n", err)
return
}
err = yaml.Unmarshal(f, &c)
if err != nil {
log.Printf("Error unmarshalling the config: %s\n", err)
return
}
return
}