gocustomurls/conf.go

53 lines
1.1 KiB
Go

package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
const CONFIG_LOG string = "/var/lib/gocustomurls/"
type ConfigFile struct {
Mappings []struct {
Protocol string `json:"protocol"`
VanityUrl string `json:"vanity_url"`
RealUrl string `json:"real_url"`
} `json:"mappings"`
}
// isFile - check if fp is a valid file
func isFile(fp string) bool {
info, err := os.Stat(fp)
if os.IsNotExist(err) || !info.Mode().IsRegular() {
return false
}
return true
}
// load mapping file
func LoadFile() (ConfigFile, error) {
var mapping ConfigFile
dirname, err := os.UserConfigDir()
if err != nil {
return mapping, err
}
configFilePath := filepath.Join(dirname, "gocustomurls/config.json")
ok := isFile(configFilePath)
if !ok {
return mapping, fmt.Errorf("%s/gocustomurls/config.json file is not found", dirname)
}
configFile, err := os.Open(configFilePath)
if err != nil {
return mapping, err
}
defer configFile.Close()
err = json.NewDecoder(configFile).Decode(&mapping)
if err != nil {
return mapping, err
}
return mapping, nil
}