patchman/server/config.go

54 lines
1.5 KiB
Go
Raw Normal View History

2023-10-26 14:56:36 +02:00
package main
import (
cryptRand "crypto/rand"
"encoding/base64"
"github.com/spf13/viper"
"log"
"os"
)
// generateSecret generates a random string to use as sane defaults for secrets
func generateSecret() string {
b := make([]byte, 64)
_, err := cryptRand.Read(b)
if err != nil {
log.Printf("Could not generate Secrets: %v", err)
return "CHANGEME"
}
return base64.StdEncoding.EncodeToString(b)
}
// loadConfig reads in the Config file(s) and sets defaults.
func loadConfig() {
viper.SetDefault("port", 8443)
viper.SetDefault("address", "0.0.0.0")
viper.SetDefault("database.ip", "127.0.0.1")
viper.SetDefault("database.port", "1486")
viper.SetDefault("database.user", "patchman")
viper.SetDefault("database.password", "CHANGEME")
viper.SetDefault("database.name", "patchman")
viper.SetDefault("sessionsecret", generateSecret())
viper.SetConfigName("server.yaml")
viper.SetConfigType("yaml")
if os.Getenv("GIN_MODE") == "release" {
viper.AddConfigPath("/etc/patchman/")
} else {
viper.AddConfigPath("./")
}
// Read Config and handle produced error, separating out File not found
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
err := viper.WriteConfig()
if err != nil {
log.Printf("Could not write config file. Running with default configuration: %w", err)
}
// Config file not found; ignore error if desired
} else {
// Config file was found but another error was produced
log.Fatalf("Could not load config: %w", err)
}
}
}