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 ( import (
"bufio" "bufio"
"errors" "errors"
"fmt"
"log" "log"
"os" "os"
"strconv" "strconv"
"strings" "strings"
) )
var ConfigFile = "config/config.txt"
type Config struct { type Config struct {
Username string Username string
Password string Password string
Port int Port int
} }
func LoadConfig() (Config, error) { func (c *Config) Save() error {
filename := "config/config.txt" 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) { f, err := os.OpenFile(ConfigFile, os.O_CREATE|os.O_WRONLY, 0644)
log.Fatal(err) if err != nil {
return Config{}, err 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 { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -50,7 +67,6 @@ func LoadConfig() (Config, error) {
} }
} }
} }
if err := scanner.Err(); err != nil { if err := scanner.Err(); err != nil {
log.Fatal(err) log.Fatal(err)
} }

View file

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