Pull out the function to read and parse config files and add some more error handling.

This commit is contained in:
root 2025-03-15 20:20:45 -04:00
parent b3df846212
commit bb1d0363f3
2 changed files with 53 additions and 27 deletions

View file

@ -3,13 +3,40 @@ package main
import (
"errors"
"fmt"
_ "strconv"
"os"
"strings"
"github.com/hjson/hjson-go/v4"
)
// Configuration errors
// Errors
var ErrUndefined = errors.New("value not defined")
var ErrFileNotFound = errors.New("file not found")
var ErrParse = errors.New("file could not be parsed")
// File and parsing errors
type ParseError struct{
File string
Err error
}
func (e *ParseError) Error() string {
return fmt.Sprintf("Error parsing configuration file %s: %s",
e.File, e.Err.Error())
}
func (e *ParseError) Unwrap() error { return e.Err }
func fileNotFoundError(file string) *ParseError {
return &ParseError{file, ErrFileNotFound}
}
func parsingError(file string) *ParseError {
return &ParseError{file, ErrParse}
}
// Config struct errors
type ConfigError struct {
Key string
Value interface{}
@ -27,6 +54,25 @@ func undefinedError(key string) *ConfigError {
return &ConfigError{key, nil, ErrUndefined}
}
func ParseConfig(file string) (Config, error) {
var err error
var c Config
fp, err := os.ReadFile(file)
if err != nil {
return Config{}, fileNotFoundError(file)
}
err = hjson.Unmarshal(fp, &c)
if err != nil {
fmt.Println(err)
return Config{}, parsingError(file)
}
return c, nil
}
// Get the first host port from a service
func (s ServiceConfig) GetHostPort() (string, error) {
if s.Ports == nil {

30
main.go
View file

@ -44,41 +44,21 @@ type ServiceConfig struct {
}
func main() {
var err error
var config Config
// Initialize structs for scripted configurations
ScriptedInit()
// Read user config file
{
file, err := os.ReadFile("goolinux.json")
if err != nil {
fmt.Println("Cannot read user config file")
fmt.Println(err)
return
}
err = hjson.Unmarshal(file, &config)
if err != nil {
fmt.Println(err)
return
}
config, err := ParseConfig("goolinux.json")
if err != nil {
fmt.Println(err)
return
}
// Read system "base" config file if it exists
if config.System.Base != "" {
var systemConfig Config
fp := "services/" + config.System.Base + ".json"
file, err := os.ReadFile(fp)
if err != nil {
fmt.Println("Cannot read system base config file")
fmt.Println(err)
return
}
err = hjson.Unmarshal(file, &systemConfig)
systemConfig, err := ParseConfig(fp)
if err != nil {
fmt.Println(err)
return