Implemented better config system
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2022-11-16 05:20:59 +01:00
parent 644f038732
commit 9f4be2d76e
12 changed files with 135 additions and 875 deletions

View File

@@ -0,0 +1,10 @@
package mqtt
type Config struct {
Host string `yaml:"host" envconfig:"MQTT_HOST"`
Port string `yaml:"port" envconfig:"MQTT_PORT"`
Username string `yaml:"username" envconfig:"MQTT_USERNAME"`
Password string `yaml:"password" envconfig:"MQTT_PASSWORD"`
ClientID string `yaml:"client_id" envconfig:"MQTT_CLIENT_ID"`
}

View File

@@ -17,33 +17,12 @@ var defaultHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Messa
fmt.Printf("MSG: %s\n", msg.Payload())
}
func Connect() MQTT {
host, ok := os.LookupEnv("MQTT_HOST")
if !ok {
host = "localhost"
}
port, ok := os.LookupEnv("MQTT_PORT")
if !ok {
port = "1883"
}
user, ok := os.LookupEnv("MQTT_USER")
if !ok {
user = "test"
}
pass, ok := os.LookupEnv("MQTT_PASS")
if !ok {
pass = "test"
}
clientID, ok := os.LookupEnv("MQTT_CLIENT_ID")
if !ok {
clientID = "automation"
}
opts := mqtt.NewClientOptions().AddBroker(fmt.Sprintf("%s:%s", host, port))
opts.SetClientID(clientID)
func Connect(config Config) MQTT {
opts := mqtt.NewClientOptions().AddBroker(fmt.Sprintf("%s:%s", config.Host, config.Port))
opts.SetClientID(config.ClientID)
opts.SetDefaultPublishHandler(defaultHandler)
opts.SetUsername(user)
opts.SetPassword(pass)
opts.SetUsername(config.Username)
opts.SetPassword(config.Password)
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {