~xenrox/faceit_checker

e03f4b24861ef1faa8d2b5a97b924434ac5836b7 — Thorben Günther 3 months ago 22a189f
config: Automatically parse config with scfg
2 files changed, 19 insertions(+), 36 deletions(-)

M config.go
M faceit.go
M config.go => config.go +15 -32
@@ 2,57 2,40 @@ package main

import (
	"fmt"
	"os"

	"git.sr.ht/~emersion/go-scfg"
)

type config struct {
	httpAddress  string
	faceitBearer string
	logLevel     string
	logFormat    string
	HttpAddress  string `scfg:"http-address"`
	FaceitBearer string `scfg:"faceit-bearer"`
	LogLevel     string `scfg:"log-level"`
	LogFormat    string `scfg:"log-format"`
}

func readConfig(path string) (*config, error) {
	cfg, err := scfg.Load(path)
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	config := new(config)
	// Set default values
	config.httpAddress = ":8080"
	config.logLevel = "info"
	config.logFormat = "text"

	d := cfg.Get("log-level")
	if d != nil {
		if err := d.ParseParams(&config.logLevel); err != nil {
			return nil, err
		}
	}

	d = cfg.Get("log-format")
	if d != nil {
		if err := d.ParseParams(&config.logFormat); err != nil {
			return nil, err
		}
	}
	config.HttpAddress = ":8080"
	config.LogLevel = "info"
	config.LogFormat = "text"

	d = cfg.Get("http-address")
	if d != nil {
		if err := d.ParseParams(&config.httpAddress); err != nil {
			return nil, err
		}
	err = scfg.NewDecoder(f).Decode(config)
	if err != nil {
		return nil, err
	}

	d = cfg.Get("faceit-bearer")
	if d == nil {
	// Check required settings
	if config.FaceitBearer == "" {
		return nil, fmt.Errorf("%q missing", "faceit-bearer")
	}
	if err := d.ParseParams(&config.faceitBearer); err != nil {
		return nil, err
	}

	return config, nil
}

M faceit.go => faceit.go +4 -4
@@ 120,7 120,7 @@ func main() {
		os.Exit(1)
	}

	logger, err := logging.New(cfg.logLevel, cfg.logFormat, os.Stderr)
	logger, err := logging.New(cfg.LogLevel, cfg.LogFormat, os.Stderr)
	if err != nil {
		slog.Error("Failed to create logger",
			slog.String("error", err.Error()))


@@ 139,7 139,7 @@ func main() {

	client := &http.Client{Timeout: time.Second * 3}

	fc := &faceitChecker{logger: logger, bearerToken: cfg.faceitBearer,
	fc := &faceitChecker{logger: logger, bearerToken: cfg.FaceitBearer,
		templates: tmpls, client: client}

	r := http.NewServeMux()


@@ 150,11 150,11 @@ func main() {

	srv := &http.Server{
		Handler:      r,
		Addr:         cfg.httpAddress,
		Addr:         cfg.HttpAddress,
		WriteTimeout: 60 * time.Second,
		ReadTimeout:  60 * time.Second,
	}
	logger.Info(fmt.Sprintf("Starting faceit_checker, listening on %s", cfg.httpAddress))
	logger.Info(fmt.Sprintf("Starting faceit_checker, listening on %s", cfg.HttpAddress))

	go func() {
		err = srv.ListenAndServe()