forked from Cliffbreak/tsviewer
69 lines
1.1 KiB
Go
69 lines
1.1 KiB
Go
package config
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"log"
|
|
"os"
|
|
)
|
|
|
|
type Config struct {
|
|
IP string `json:"ip"`
|
|
Port uint16 `json:"port"`
|
|
User User `json:"user"`
|
|
Server Server `json:"server"`
|
|
}
|
|
|
|
type User struct {
|
|
Name string `json:"name"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
type Server struct {
|
|
Port uint16 `json:"port"`
|
|
}
|
|
|
|
const FileName = "config.json"
|
|
|
|
func New() (*Config, error) {
|
|
config := defaults()
|
|
|
|
configFile, err := os.Open(FileName)
|
|
if err != nil {
|
|
if err := config.createFile(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
log.Println(config)
|
|
return &config, nil
|
|
}
|
|
defer configFile.Close()
|
|
|
|
jsonParser := json.NewDecoder(configFile)
|
|
jsonParser.Decode(&config)
|
|
|
|
return &config, nil
|
|
}
|
|
|
|
func (config Config) createFile() error {
|
|
configJSON, err := json.MarshalIndent(config, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return ioutil.WriteFile(FileName, configJSON, 0644)
|
|
}
|
|
|
|
func defaults() Config {
|
|
return Config{
|
|
IP: "127.0.0.1",
|
|
Port: 10011,
|
|
User: User{
|
|
Name: "serveradmin",
|
|
Password: "",
|
|
},
|
|
Server: Server{
|
|
Port: 9987,
|
|
},
|
|
}
|
|
}
|