Allow configuration file to be passed as parameter

This commit is contained in:
TwinProduction 2019-12-04 16:44:35 -05:00
parent 66e48609b4
commit c9c076a959
3 changed files with 51 additions and 18 deletions

View File

@ -5,6 +5,7 @@ import (
"github.com/TwinProduction/gatus/core"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"os"
"time"
)
@ -15,28 +16,44 @@ type Config struct {
}
var (
ErrNoServiceInConfig = errors.New("configuration file should contain at least 1 service")
config *Config
ErrNoServiceInConfig = errors.New("configuration file should contain at least 1 service")
ErrConfigFileNotFound = errors.New("configuration file not found")
ErrConfigNotLoaded = errors.New("configuration is nil")
config *Config
)
func Get() *Config {
if config == nil {
cfg, err := readConfigurationFile("config.yaml")
if err != nil {
if os.IsNotExist(err) {
cfg, err = readConfigurationFile("config.yml")
if err != nil {
panic(err)
}
} else {
panic(err)
}
}
config = cfg
panic(ErrConfigNotLoaded)
}
return config
}
func Load(configFile string) error {
log.Printf("[config][Load] Attempting to load config from configFile=%s", configFile)
cfg, err := readConfigurationFile(configFile)
if err != nil {
if os.IsNotExist(err) {
return ErrConfigFileNotFound
} else {
return err
}
}
config = cfg
return nil
}
func LoadDefaultConfiguration() error {
err := Load("config.yaml")
if err != nil {
if err == ErrConfigFileNotFound {
return Load("config.yml")
}
return err
}
return nil
}
func readConfigurationFile(fileName string) (config *Config, err error) {
var bytes []byte
if bytes, err = ioutil.ReadFile(fileName); err == nil {

20
main.go
View File

@ -8,20 +8,36 @@ import (
"github.com/prometheus/client_golang/prometheus/promhttp"
"log"
"net/http"
"os"
)
func main() {
go watchdog.Monitor()
cfg := loadConfiguration()
go watchdog.Monitor(cfg)
http.HandleFunc("/api/v1/results", serviceResultsHandler)
http.HandleFunc("/health", healthHandler)
http.Handle("/", http.FileServer(http.Dir("./static")))
if config.Get().Metrics {
if cfg.Metrics {
http.Handle("/metrics", promhttp.Handler())
}
log.Println("[main][main] Listening on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func loadConfiguration() *config.Config {
args := os.Args
var err error
if len(args) == 2 {
err = config.Load(args[1])
} else {
err = config.LoadDefaultConfiguration()
}
if err != nil {
panic(err)
}
return config.Get()
}
func serviceResultsHandler(writer http.ResponseWriter, _ *http.Request) {
serviceResults := watchdog.GetServiceResults()
writer.WriteHeader(http.StatusOK)

View File

@ -18,8 +18,8 @@ func GetServiceResults() *map[string][]*core.Result {
return &serviceResults
}
func Monitor() {
for _, service := range config.Get().Services {
func Monitor(cfg *config.Config) {
for _, service := range cfg.Services {
go func(service *core.Service) {
for {
log.Printf("[watchdog][Monitor] Monitoring serviceName=%s", service.Name)