package main import ( "bufio" "errors" "fmt" "os" "sort" "strings" ) func FileExists(path string) bool { _, err := os.Stat(path) return !errors.Is(err, os.ErrNotExist) } func LoadConfig(filename string) (map[string]string, error) { var results map[string]string = make(map[string]string) file, err := os.Open(filename) if err != nil { return results, err } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() if len(line) == 0 { continue } if line[0] == '#' { continue } // Ok, I have a line, now what? parts := strings.SplitN(line, ": ", 2) if len(parts) == 2 { parts[1] = strings.Trim(parts[1], " ") // Handle quoted values if parts[1][0] == '"' && parts[1][len(parts[1])-1] == '"' { parts[1] = parts[1][1 : len(parts[1])-1] } if parts[1][0] == '\'' && parts[1][len(parts[1])-1] == '\'' { parts[1] = parts[1][1 : len(parts[1])-1] } results[parts[0]] = parts[1] // } else { // fmt.Printf("I'm not sure about [%s]\n", line) } } return results, nil } func SaveConfig(filename string, config map[string]string) error { file, err := os.Create(filename) if err != nil { return err } defer file.Close() // Sort the Keys var keys []string for key := range config { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { fmt.Fprintf(file, "%s: %s\n", key, config[key]) } return nil } // SetConfigDefault Set default value (if not present) func SetConfigDefault(config *map[string]string, key string, value string) bool { _, ok := (*config)[key] (*config)[key] = value return ok }