hibiscus/config.go

100 lines
1.9 KiB
Go
Raw Normal View History

2024-03-17 17:12:41 +03:00
package main
import (
"bufio"
"errors"
2024-03-18 15:22:50 +03:00
"fmt"
2024-03-17 17:12:41 +03:00
"log"
"os"
2024-03-23 15:36:01 +03:00
"reflect"
2024-03-17 17:12:41 +03:00
"strconv"
"strings"
)
2024-03-18 15:22:50 +03:00
var ConfigFile = "config/config.txt"
2024-03-17 17:12:41 +03:00
type Config struct {
2024-03-23 15:36:01 +03:00
Username string `config:"username"`
Password string `config:"password"`
Port int `config:"port"`
2024-03-20 16:18:23 +03:00
2024-03-23 15:36:01 +03:00
TelegramToken string `config:"tg_token"`
TelegramChat string `config:"tg_chat"`
2024-03-17 17:12:41 +03:00
}
2024-03-18 15:22:50 +03:00
func (c *Config) Save() error {
2024-03-23 15:36:01 +03:00
output := ""
v := reflect.ValueOf(*c)
typeOfS := v.Type()
for i := 0; i < v.NumField(); i++ {
key := typeOfS.Field(i).Tag.Get("config")
value := v.Field(i).Interface()
if value != "" {
output += fmt.Sprintf("%s=%v\n", key, value)
}
2024-03-20 16:18:23 +03:00
}
2024-03-17 17:12:41 +03:00
2024-03-18 15:22:50 +03:00
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
2024-03-17 17:12:41 +03:00
}
2024-03-18 15:22:50 +03:00
return nil
}
2024-03-17 17:12:41 +03:00
2024-03-20 00:02:22 +03:00
func (c *Config) Reload() error {
2024-03-18 15:22:50 +03:00
if _, err := os.Stat(ConfigFile); errors.Is(err, os.ErrNotExist) {
2024-03-20 00:02:22 +03:00
err := c.Save()
2024-03-18 15:22:50 +03:00
if err != nil {
2024-03-20 00:02:22 +03:00
return err
2024-03-18 15:22:50 +03:00
}
2024-03-20 00:02:22 +03:00
return nil
2024-03-18 15:22:50 +03:00
}
file, err := os.Open(ConfigFile)
2024-03-17 17:12:41 +03:00
if err != nil {
2024-03-20 00:02:22 +03:00
return err
2024-03-17 17:12:41 +03:00
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
entry := strings.Split(strings.Replace(scanner.Text(), " ", "", -1), "=")
if len(entry) != 2 {
continue
}
key := entry[0]
value := entry[1]
if key == "username" {
2024-03-20 00:02:22 +03:00
c.Username = value
2024-03-17 17:12:41 +03:00
} else if key == "password" {
2024-03-20 00:02:22 +03:00
c.Password = value
2024-03-17 17:12:41 +03:00
} else if key == "port" {
numVal, err := strconv.Atoi(value)
if err == nil {
2024-03-20 00:02:22 +03:00
c.Port = numVal
2024-03-17 17:12:41 +03:00
}
2024-03-20 16:18:23 +03:00
} else if key == "tg_token" {
c.TelegramToken = value
} else if key == "tg_chat" {
c.TelegramChat = value
2024-03-17 17:12:41 +03:00
}
}
if err := scanner.Err(); err != nil {
2024-03-20 00:02:22 +03:00
return err
2024-03-17 17:12:41 +03:00
}
2024-03-20 00:02:22 +03:00
return nil
}
func ConfigInit() Config {
cfg := Config{Port: 7101, Username: "admin", Password: "admin"} // Default values are declared here, I guess
err := cfg.Reload()
if err != nil {
log.Fatal(err)
}
return cfg
2024-03-17 17:12:41 +03:00
}