57 lines
1.1 KiB
Go
57 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"os"
|
|
)
|
|
|
|
const configPath = "config.json"
|
|
|
|
type config struct {
|
|
Port int `json:"port"`
|
|
ThemeName string `json:"theme"`
|
|
}
|
|
|
|
// createDefaultConfig checks if a config file is present. If not, it creates the default config file.
|
|
// It returns true if a file is created.
|
|
func createDefaultConfig() (bool, error) {
|
|
info, err := os.Stat(configPath)
|
|
if err == nil {
|
|
if info.IsDir() {
|
|
return false, errors.New("config.json is a directory")
|
|
}
|
|
return false, nil
|
|
}
|
|
if !os.IsNotExist(err) {
|
|
return false, err
|
|
}
|
|
|
|
// Create the file.
|
|
f, err := os.Create(configPath)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
encoder := json.NewEncoder(f)
|
|
encoder.SetIndent("", "\t")
|
|
err = encoder.Encode(config{
|
|
Port: 80,
|
|
ThemeName: "default",
|
|
})
|
|
return true, err
|
|
}
|
|
|
|
// parseConfig parses the config file into a struct
|
|
func parseConfig() (config, error) {
|
|
// Open the file.
|
|
f, err := os.Open(configPath)
|
|
if err != nil {
|
|
return config{}, err
|
|
}
|
|
defer f.Close()
|
|
// Decode it into the config struct.
|
|
var cfg config
|
|
err = json.NewDecoder(f).Decode(&cfg)
|
|
return cfg, err
|
|
}
|