add default config creation

This commit is contained in:
Andrew-71 2024-03-18 15:22:50 +03:00
parent 7b09e5e7b5
commit b807a65c0e
2 changed files with 27 additions and 11 deletions

View file

@ -3,29 +3,46 @@ package main
import (
"bufio"
"errors"
"fmt"
"log"
"os"
"strconv"
"strings"
)
var ConfigFile = "config/config.txt"
type Config struct {
Username string
Password string
Port int
}
func LoadConfig() (Config, error) {
filename := "config/config.txt"
func (c *Config) Save() error {
output := fmt.Sprintf("port=%d\nusername=%s\npassword=%s", c.Port, c.Username, c.Password)
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
log.Fatal(err)
return Config{}, err
f, err := os.OpenFile(ConfigFile, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
if _, err := f.Write([]byte(output)); err != nil {
return err
}
return nil
}
cfg := Config{Port: 7101}
func LoadConfig() (Config, error) {
cfg := Config{Port: 7101, Username: "admin", Password: "admin"} // Default values are declared here, I guess
file, err := os.Open(filename)
if _, err := os.Stat(ConfigFile); errors.Is(err, os.ErrNotExist) {
err := cfg.Save()
if err != nil {
return cfg, err
}
return cfg, nil
}
file, err := os.Open(ConfigFile)
if err != nil {
log.Fatal(err)
}
@ -50,7 +67,6 @@ func LoadConfig() (Config, error) {
}
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}

View file

@ -1,3 +1,3 @@
port=7101
username=test
password=pass
username=admin
password=admin