mirror of
https://github.com/therootcompany/golib.git
synced 2026-04-24 20:58:00 +00:00
The old ParseConf opened the file itself, which the name did not convey. Now it parses the config text directly, matching encoding/json.Unmarshal-style conventions: callers read the file (or source the string however they like) and pass it in. Also introduce errors.ErrMissingCredentials for the credential-missing case so callers can branch on it.
52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
package geoip
|
|
|
|
import (
|
|
"bufio"
|
|
"errors"
|
|
"strings"
|
|
)
|
|
|
|
// Conf holds the fields parsed from a geoipupdate-style config file.
|
|
type Conf struct {
|
|
AccountID string
|
|
LicenseKey string
|
|
EditionIDs []string
|
|
DatabaseDirectory string
|
|
}
|
|
|
|
// ErrMissingCredentials is returned by ParseConf when AccountID or LicenseKey
|
|
// is absent from the input.
|
|
var ErrMissingCredentials = errors.New("AccountID and LicenseKey are required")
|
|
|
|
// ParseConf parses a geoipupdate-style config (whitespace-separated key/value
|
|
// pairs, # comments). Compatible with GeoIP.conf files used by the official
|
|
// geoipupdate tool.
|
|
func ParseConf(s string) (*Conf, error) {
|
|
kv := make(map[string]string)
|
|
scanner := bufio.NewScanner(strings.NewReader(s))
|
|
for scanner.Scan() {
|
|
line := strings.TrimSpace(scanner.Text())
|
|
if line == "" || strings.HasPrefix(line, "#") {
|
|
continue
|
|
}
|
|
key, value, _ := strings.Cut(line, " ")
|
|
kv[strings.TrimSpace(key)] = strings.TrimSpace(value)
|
|
}
|
|
if err := scanner.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
c := &Conf{
|
|
AccountID: kv["AccountID"],
|
|
LicenseKey: kv["LicenseKey"],
|
|
DatabaseDirectory: kv["DatabaseDirectory"],
|
|
}
|
|
if c.AccountID == "" || c.LicenseKey == "" {
|
|
return nil, ErrMissingCredentials
|
|
}
|
|
if ids := kv["EditionIDs"]; ids != "" {
|
|
c.EditionIDs = strings.Fields(ids)
|
|
}
|
|
return c, nil
|
|
}
|