2019-01-14 20:07:11 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Config struct {
|
2019-01-15 00:46:39 +00:00
|
|
|
IP string `json:"ip"`
|
|
|
|
Port uint16 `json:"port"`
|
|
|
|
User User `json:"user"`
|
|
|
|
Server Server `json:"server"`
|
2019-01-14 20:07:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type User struct {
|
|
|
|
Name string `json:"name"`
|
|
|
|
Password string `json:"password"`
|
|
|
|
}
|
|
|
|
|
2019-01-15 00:46:39 +00:00
|
|
|
type Server struct {
|
|
|
|
Port uint16 `json:"port"`
|
|
|
|
}
|
|
|
|
|
2019-01-14 20:07:11 +00:00
|
|
|
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: "",
|
|
|
|
},
|
2019-01-15 00:46:39 +00:00
|
|
|
Server: Server{
|
|
|
|
Port: 9987,
|
|
|
|
},
|
2019-01-14 20:07:11 +00:00
|
|
|
}
|
|
|
|
}
|