1
0
Fork 0
hats/pkg/config/config.go

95 lines
2.5 KiB
Go
Raw Normal View History

2023-10-12 17:23:35 +00:00
package config
import (
"fmt"
"log/slog"
2023-10-12 17:23:35 +00:00
"strconv"
"strings"
2023-10-12 17:23:35 +00:00
"code.jhot.me/jhot/hats/internal/util"
)
type HatsConfig struct {
LogLevl string
HomeAssistantHost string
HomeAssistantPort string
HomeAssistantSecure bool
HomeAssistantToken string
2023-10-12 17:23:35 +00:00
NatsHost string
NatsPort string
NatsToken string
NatsClientName string
2023-10-13 20:31:23 +00:00
HatsHost string
HatsPort string
HatsSecure bool
2023-11-08 23:12:04 +00:00
NtfyHost string
NtfyToken string
2023-10-12 17:23:35 +00:00
}
func FromEnvironment() *HatsConfig {
config := &HatsConfig{
LogLevl: util.GetEnvWithDefault("LOG_LEVEL", "INFO"),
2023-10-12 17:23:35 +00:00
HomeAssistantHost: util.GetEnvWithDefault("HASS_HOST", "127.0.0.1"),
HomeAssistantPort: util.GetEnvWithDefault("HASS_PORT", "8123"),
HomeAssistantToken: util.GetEnvWithDefault("HASS_TOKEN", ""),
NatsHost: util.GetEnvWithDefault("NATS_HOST", "127.0.0.1"),
NatsPort: util.GetEnvWithDefault("NATS_PORT", "4222"),
NatsToken: util.GetEnvWithDefault("NATS_TOKEN", ""),
NatsClientName: util.GetEnvWithDefault("NATS_CLIENT_NAME", "hats"),
2023-10-13 20:31:23 +00:00
HatsHost: util.GetEnvWithDefault("HATS_HOST", "hats"),
HatsPort: util.GetEnvWithDefault("HATS_PORT", "8888"),
2023-11-08 23:12:04 +00:00
NtfyHost: util.GetEnvWithDefault("NTFY_HOST", "https://ntfy.sh"),
NtfyToken: util.GetEnvWithDefault("NTFY_TOKEN", ""),
2023-10-12 17:23:35 +00:00
}
config.HomeAssistantSecure, _ = strconv.ParseBool(util.GetEnvWithDefault("HASS_SECURE", "false"))
config.HatsSecure, _ = strconv.ParseBool(util.GetEnvWithDefault("HATS_SECURE", "false"))
return config
}
func (c *HatsConfig) GetHomeAssistantBaseUrl() string {
2023-10-12 17:23:35 +00:00
hassProtocol := "http"
if c.HomeAssistantSecure {
2023-10-12 17:23:35 +00:00
hassProtocol += "s"
}
return fmt.Sprintf("%s://%s:%s", hassProtocol, c.HomeAssistantHost, c.HomeAssistantPort)
}
2023-10-13 20:31:23 +00:00
func (c *HatsConfig) GetHomeAssistantWebsocketUrl() string {
protocol := "ws"
if c.HomeAssistantSecure {
protocol += "s"
}
return fmt.Sprintf("%s://%s:%s/api/websocket", protocol, c.HomeAssistantHost, c.HomeAssistantPort)
}
2023-10-12 17:23:35 +00:00
func (c *HatsConfig) GetNatsBaseUrl() string {
return fmt.Sprintf("nats://%s:%s", c.NatsHost, c.NatsPort)
}
func (c *HatsConfig) GetHatsBaseUrl() string {
protocol := "http"
if c.HomeAssistantSecure {
protocol += "s"
2023-10-13 20:31:23 +00:00
}
return fmt.Sprintf("%s://%s:%s", protocol, c.HatsHost, c.HatsPort)
}
2023-10-13 20:31:23 +00:00
func (c *HatsConfig) GetLogLevel() slog.Level {
switch strings.ToLower(c.LogLevl) {
case "error":
return slog.LevelError
case "warn":
return slog.LevelWarn
case "debug":
return slog.LevelDebug
default:
return slog.LevelInfo
}
2023-10-12 17:23:35 +00:00
}