Configuration to object, reflection or abstract factory?


(Luca Cavalllin) #1

I have a tiny IoT tool that given some configuration with sensor name and pin will read from these.
Let’s say I have:

sensors:
    temperature:
        pin: 3

I want to parse this configuration so a new temperature sensor is created and listening to pin 3.
What is the best way to do so? Reflection? Abstract factories? I want to avoid a long list of switch which I find not very elegant.

Thanks!


(Johan Dahl) #2

It looks like yaml (https://en.wikipedia.org/wiki/YAML) and if so could you use the packade https://github.com/go-yaml/yaml to decode it like this

package main

import (
	"fmt"

	"gopkg.in/yaml.v2"
)

type T struct {
	Sensors struct {
		Temperature struct {
			Pin int
		}
	}
}

func main() {
	var data = `sensors:
    temperature:
        pin: 3`

	t := T{}

	err := yaml.Unmarshal([]byte(data), &t)
	if err != nil {
		panic(err)
	}
	fmt.Printf("t:%#v\n", t)
	fmt.Printf("pin: %d\n", t.Sensors.Temperature.Pin)
}