xconfig

package module
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 9, 2026 License: MIT Imports: 10 Imported by: 13

README

Go Report Card GoDoc GolangCI

XConfig for GO v1

Package xconfig loads a configuration file similar to a .ini file, but with some important improvements:

  • The xconfig recognize bool, int, float and Strings, and also collections of values and hierarchical nested sub-config sets.
  • The xconfig is compatible with XDataset to inject and use in templates, database records, etc.
  • You can load more than one file in merge mode or replacing mode in the same config object.
  • You can set and get parameters at any time.
  • You can load the config object based on a file, but also on a string and another object; this way you can serialize, unserialize, transfer by any stream, save or load on database the object, etc.
  • You can also save back the config string with all its comments.

Manuals are available on godoc.org GoDoc

TO DO:

  • Add Time ? Other types of int32, int64, float32, runes etc ?
  • Merge vs load to load more than 1 file (pending)
  • Add a flag when it's a multiple load to warn a "save"
  • Add error control con Get* for type conversions (if the type is different as expected)
  • Log errors into official log

Version Changes Control

v0.5.0 - 2026-05-27

  • Big security and corrections update
  • Documentation enhanced directly into the code for pkg.go.dev
  • SaveFile now user 0644 correct unix mask
  • ioutil deprecated, now uses io and os
  • Verify safe paths with reading/writing files
  • The code is now thread-safe and racing safe
  • Operators := and += are finally implemented as they must work
  • Del operation is now safe and does not break anymore the configuration variables
  • helper functions added, add, parsemap enhanced because of some errors
  • Clone is now really cloning (deep clone of sub configs and arrays)
  • Set now parse keys with dots, like Get
  • buildLevel preserve the " for strings that are not obvious strings
  • String and buildleve does not panic anymore in case of empty lines and empty keys
  • Remove AnalyzeKey that is never used
  • Remove multithread property that is never used

v0.4.3 - 2021-11-16

  • Documentation revised and added with Marshal and SaveFile Functions
  • Bug corrected in Marshal, sometimes an empty line was ignored by the reconstruction of the string

v0.4.2 - 2020-03-30

  • Pointers to self structure changed (c.Parameters instead of (*c).Parameters)
  • Del/Set/Add function now work correctly and do not duplicate entries if not merged (Add)

v0.4.1 - 2020-03-29

  • Marshal and SaveFile implemented to generate original string of XConfig file and save it to a file.
  • example directory removed. The examples are implicitly into documentation and tests.

v0.4.0 - 2020-03-29

  • Modulatization (go mod init) and use of xcore/v2
  • Documentation finished
  • Comments into code, corrections to meet golint standards
  • String modified to order printed lines and get a uniform result if the XConfig contains the same data
  • Tests implemented to verify official defined specs

v0.3.0 - 2020-02-11

  • Documentation enhanced, Configuration Syntax Reference added
  • Licence and Tests Added

v0.2.1 - 2020-02-10

  • Documentation enhanced
  • Bug corrected on String and GoString()

v0.2.0 - 2020-02-10

  • Modification to XConfig to meet xcore v1.0.0 (.String and .GoString functions added, .Stringify function removed)

v0.1.0 - 2019-12-06

  • Code formated before sending to github (gofmt -s)

v0.0.9 - 2019-07-12

  • Incode println removed

v0.0.8 - 2019-06-25

  • Added Clone functions to meet xcore.XDatasetDef definition

v0.0.7 - 2019-03-06

  • Added functions of Time to get time data.

v0.0.6 - 2019-02-05

  • Added conversion between types con Get* functions

v0.0.5 - 2019-01-06

  • XConfig object aligned with XDataset with missing set of functions
  • XConfig csn now be injected into an XTemplate

V0.0.4 - 2018-12-21

  • Added GetString, GetInt, GetBool and GetFloat to directly get the known value type (and do not have to convert types)
  • Error corrected on Set (type float added)

V0.0.3 - 2018-12-05

Branch "late-night" added to github

  • Added support for sub-XConfig with entry1.entry2.entry3=xxx

V0.0.2 - 2018-11-27

  • Added support for strings starting with "
  • Added support for array of booleans
  • Added support for float parameters
  • Work for a full normal load of a file, suporting also repeated parameters (array of parameters)
  • VERSION constant added
  • XConfig.Get function implemented for basic parameters (without + or :)

V0.0.1 - 2018-11-14

  • First commit, only work to load basic parameters

Documentation

Overview

Package xconfig provides a thread-safe, ordered configuration manager that reads and writes .conf files in a structured key=value format.

It extends the classic INI-file concept with automatic type inference, multi-value arrays, nested sub-configurations via dotted key notation, and full compatibility with the xcore.XDatasetDef interface for use in templates, database adapters, and other xcore-aware components.

Installation

go get -u github.com/webability-go/xconfig

Quick start

xc := xconfig.New()

if err := xc.LoadFile("app.conf"); err != nil {
    log.Fatal(err)
}

host, _ := xc.GetString("host")
port, _ := xc.GetInt("port")
debug, _ := xc.GetBool("debug")

xc.Set("build", "1.2.3")

if err := xc.SaveFile("app.conf"); err != nil {
    log.Fatal(err)
}

File format

Configuration files are UTF-8 plain text. Lines beginning with # or ; are treated as comments and are preserved verbatim during serialisation. Blank lines are also preserved. All other lines must follow one of the three assignment forms:

key=value           # normal assignment
key:=value          # force-replace — overwrites even when merging
key+=value          # force-add    — appends even when loading

Keys are case-sensitive and must not contain whitespace or the '=' character. Leading and trailing whitespace around both the key and the value is trimmed automatically. An empty key is silently ignored.

A complete example file:

# app.conf
; semicolons are also comments

host=db.example.com
port=5432
debug=false

# repeated keys become arrays
tag=stable
tag=v2

# dotted keys create nested sub-configurations
cache.host=redis.example.com
cache.port=6379
cache.ttl=300

# per-entry operator overrides
host:=override.example.com   # always replaces, even in MergeFile
tag+=canary                  # always appends,  even in LoadFile

Type inference

The parser infers the stored Go type from the raw value string:

Value in file              Stored Go type   Stored value
─────────────────────────  ───────────────  ────────────
true  / on  / yes         bool             true
false / off / no / none   bool             false
42, -7, 1000000           int              (integer)
3.14, -0.5, 1.5e-3        float64          (float)
anything else             string           (as-is)

Because the parser tries bool → int → float → string in that order, values such as "1" become int, and "1.0" become float64. Use the forced-string prefix described below if you need to store such values as strings.

Forced-string prefix

Prefixing a value with a double-quote character (") forces string storage regardless of the value content, and the prefix itself is stripped:

count="123          # stores the string  "123"  (not int 123)
flag="true          # stores the string  "true" (not bool true)
ratio="1.0          # stores the string  "1.0"  (not float 1.0)
empty="             # stores the string  ""

To store a string whose first character is itself a double-quote, use two consecutive double-quote characters as the prefix:

label=""+quoted     # stores the string  `"+quoted`

[Marshal] and XConfig.SaveFile restore these prefixes automatically, so a save-then-load cycle is always lossless.

Multi-value parameters (arrays)

Repeating a key on successive lines promotes the stored value from a scalar to a typed slice. Values are appended in the order they appear in the file:

country=MX
country=US
country=FR
# → country  []string{"MX", "US", "FR"}

port=8080
port=8081
port=8082
# → port  []int{8080, 8081, 8082}

ratio=0.25
ratio=0.75
# → ratio  []float64{0.25, 0.75}

flag=true
flag=false
# → flag  []bool{true, false}

All values for a given key must be of the same inferred type. Mixing types (e.g. an int followed by a bool for the same key) returns an error.

Nested sub-configurations

A dot in a key name creates a hierarchy. Each segment names a sub-XConfig:

database.host=db.example.com
database.port=5432
database.tls=true
# → "database" is a *XConfig containing host, port, tls

Nesting can be arbitrarily deep:

app.cache.redis.host=cache.example.com
app.cache.redis.port=6379
app.cache.redis.ttl=60

Sub-configurations are accessed via XConfig.GetConfig:

db := xc.GetConfig("database")
if db != nil {
    host, _ := db.GetString("host")
    port, _ := db.GetInt("port")
}

Dotted keys can also be set programmatically. XConfig.Set and XConfig.Add accept dotted paths and create the necessary sub-XConfig hierarchy:

xc.Set("database.host", "db.example.com")
xc.Set("database.port", 5432)

Assignment operators

The three assignment operators control how a value combines with any existing entry that already has the same key, both within a single file and across multiple Load/Merge calls:

=   default — behaviour depends on the Load* or Merge* function used:
              Load* replaces existing entries; Merge* appends to them.

:=  force-replace — always overwrites the current value, regardless of
                    whether the caller used a Load* or Merge* function.
                    When := appears later in the same file than a plain =
                    for the same key, it replaces whatever was built up
                    before it in that file.

+=  force-add — always appends to the current value, regardless of
                whether the caller used a Load* or Merge* function.
                Useful for unconditionally extending an array defined
                in a base file.

Examples of operator interactions:

# defaults.conf
host=primary.example.com
tag=stable

# local.conf  (loaded with MergeFile)
host:=override.example.com   # replaces host even in merge mode
tag+=canary                  # appends canary even in merge mode
# result: host="override.example.com", tag=[]string{"stable","canary"}

Loading and merging

XConfig provides three families of source loaders, each with a Load variant (replaces existing entries) and a Merge variant (appends to existing entries):

Source      Load           Merge
──────────  ─────────────  ──────────────
File        LoadFile       MergeFile
String      LoadString     MergeString
*XConfig    LoadXConfig    MergeXConfig

A common pattern for layered configuration (defaults, environment, local overrides):

xc := xconfig.New()
xc.LoadFile("config/defaults.conf")          // base values
xc.MergeFile("config/production.conf")       // environment overrides
xc.MergeFile("config/local.conf")            // developer-local tweaks
// Missing files are silently ignored if you wrap with os.IsNotExist.

When a Merge* call is made into a non-empty XConfig, the Multiple field is set to true, indicating that the data originates from more than one source.

Getting values

The raw value stored for a key is retrieved with XConfig.Get, which returns (interface{}, bool). The concrete type of the interface is one of: string, int, float64, bool, []string, []int, []float64, []bool, time.Time, []time.Time, or *XConfig.

Type-specific getters perform automatic cross-type conversions:

Getter              Returns     Converts from
──────────────────  ──────────  ───────────────────────────────────
GetString(key)      string      any type via fmt.Sprint
GetInt(key)         int         float64 (truncated), bool (0 or 1)
GetFloat(key)       float64     int (widened), bool (0.0 or 1.0)
GetBool(key)        bool        int (!=0), float64 (!=0)
GetTime(key)        time.Time   no conversion; must be exact type
GetConfig(key)      *XConfig    no conversion; must be exact type
GetDataset(key)     XDatasetDef same as GetConfig

Collection getters return typed slices and wrap single scalars in a one-element slice, so callers can always range over the result:

GetStringCollection(key)  →  []string
GetIntCollection(key)     →  []int
GetFloatCollection(key)   →  []float64
GetBoolCollection(key)    →  []bool
GetTimeCollection(key)    →  []time.Time

All getters return (zero-value, false) when the key does not exist.

Setting and deleting values

XConfig.Set creates or replaces the entry for a key. It accepts string, int, float64, and bool values, and supports dotted paths:

xc.Set("host", "localhost")
xc.Set("port", 5432)
xc.Set("tls", true)
xc.Set("database.host", "db.example.com")   // dotted path

XConfig.Add appends a value to a key, building a slice on the first repeated call. It accepts the same types as Set:

xc.Add("tag", "stable")
xc.Add("tag", "v2")
// tag is now []string{"stable", "v2"}

XConfig.Del removes a key entirely, including from the insertion order so that subsequent serialisation does not include it:

xc.Del("temp")

Serialisation

XConfig.Marshal returns the full configuration as a string in the .conf file format. It preserves comments, blank lines, and insertion order. String values that would be misinterpreted on reload are automatically protected with the " prefix, making the round-trip lossless:

xc.Set("label", "true")          // stored as string
text := xc.Marshal()             // produces:  label="true
xc2 := xconfig.New()
xc2.LoadString(text)
v, _ := xc2.GetString("label")   // "true"  ← string, not bool

XConfig.SaveFile writes the same output to a file with mode 0644.

XConfig.String returns a compact, human-readable debug dump (not suitable for reloading); its format is XConfig[\nkey:value\n...\n].

Cloning

XConfig.Clone returns a fully independent deep copy of the XConfig. All nested sub-configurations and all array slices are recursively cloned, so modifications to the clone do not affect the original and vice versa:

snapshot := xc.Clone().(*xconfig.XConfig)
snapshot.Set("env", "test")
// xc is unchanged

Thread safety

All public methods are safe for concurrent use from multiple goroutines. Read operations (Get*, Clone, Marshal, String) acquire a shared read lock. Write operations (Load*, Merge*, Set, Add, Del, SaveFile) acquire an exclusive write lock.

The internal mutex is never held while sub-XConfig values are accessed through the pointer returned by XConfig.GetConfig. If callers share a sub-XConfig pointer across goroutines, they must provide their own synchronisation for those accesses.

Path safety

XConfig.LoadFile, XConfig.MergeFile, and XConfig.SaveFile reject filenames that contain path-traversal sequences (..), returning an error rather than reading or writing a file outside the intended directory tree.

Index

Constants

View Source
const VERSION = "0.5.0"

VERSION is the semantic version of the XConfig library.

Variables

This section is empty.

Functions

This section is empty.

Types

type Parameter

type Parameter struct {
	Value interface{}
	// contains filtered or unexported fields
}

Parameter is an internal storage unit for a single configuration entry.

It pairs a typed value with the type code inferred by the parser and the assignment operator recorded from the source file. The type code determines how subsequent Add or Merge operations combine this entry with new values.

Type codes:

0  = unset (zero value; not yet assigned)
1  = string       11 = []string
2  = int          12 = []int
3  = float64      13 = []float64
4  = bool         14 = []bool
21 = *XConfig (nested sub-configuration)

Assignment codes:

0  = default (follows the Load*/Merge* call semantics)
1  = force-replace (:= operator — always overwrites)
2  = force-add     (+= operator — always appends)

func (*Parameter) Clone

func (p *Parameter) Clone() *Parameter

Clone returns a fully independent deep copy of the Parameter.

Slice backing arrays ([]string, []int, []float64, []bool) are copied into freshly allocated slices so that the original and the clone never share underlying storage. Nested *XConfig values are cloned recursively via their own Clone method.

type XConfig

type XConfig struct {
	Parameters map[string]Parameter
	Comments   map[string]string
	Order      []string
	Multiple   bool
	// contains filtered or unexported fields
}

XConfig is a thread-safe, ordered key-value configuration store.

Parameters maps each key to its typed Parameter value. Comments maps sentinel keys of the form "#<n>" to the corresponding comment or blank line text, preserving them across serialisation round-trips. Order records the insertion sequence of both parameters and comments, which is reproduced faithfully by Marshal and SaveFile. Multiple is set to true the first time a second source is merged into this config, indicating that the data originates from more than one file or string.

An XConfig must be created via New; a zero value is not ready for use.

func New

func New() *XConfig

New creates and returns an empty XConfig ready for use.

xc := xconfig.New()
xc.Set("host", "localhost")
xc.Set("port", 5432)

func (*XConfig) Add

func (c *XConfig) Add(key string, value interface{}) error

Add appends value to the entry for key, building a typed slice when the key already holds a scalar value of the same type.

Accepted value types are string, int, float64, and bool. Passing a value of any other type returns an error. Appending a value whose type is incompatible with the existing entry (e.g. adding a bool to an int key) also returns an error; the configuration is not modified in that case.

xc.Add("country", "MX")
xc.Add("country", "US")
xc.Add("country", "FR")
countries, _ := xc.GetStringCollection("country")
// countries == []string{"MX", "US", "FR"}

xc.Add("port", 8080)
xc.Add("port", 8081)
ports, _ := xc.GetIntCollection("port")
// ports == []int{8080, 8081}

Add returns a non-nil error when key is the empty string.

func (*XConfig) Clone

func (c *XConfig) Clone() xcore.XDatasetDef

Clone returns a fully independent deep copy of the XConfig as an xcore.XDatasetDef. All nested sub-configurations and all array slices are recursively cloned; modifying the clone does not affect the original, and modifying the original does not affect the clone.

The returned value can be type-asserted to *XConfig when a concrete type is needed:

snapshot := original.Clone().(*xconfig.XConfig)
snapshot.Set("env", "test")
// original remains unchanged

func (*XConfig) Del

func (c *XConfig) Del(key string)

Del removes the entry for key from the configuration. If the key does not exist, Del is a no-op. The key is removed from Parameters, Comments, and Order, so subsequent calls to Marshal, SaveFile, String, and iteration via Order will not include it.

xc.Set("temp", "scratch")
xc.Del("temp")
_, exists := xc.Get("temp")  // exists == false

func (*XConfig) Get

func (c *XConfig) Get(key string) (interface{}, bool)

Get returns the raw value stored under key and a boolean indicating whether the key was found. The concrete type of the returned interface{} is one of: string, int, float64, bool, []string, []int, []float64, []bool, or *XConfig.

Returns (nil, false) when the key does not exist.

if v, ok := xc.Get("port"); ok {
    fmt.Println(v)        // e.g. 5432 (int)
    fmt.Printf("%T\n", v) // "int"
}

func (*XConfig) GetBool

func (c *XConfig) GetBool(key string) (bool, bool)

GetBool returns the value of key as a bool. Non-zero int and float64 values are true; zero values are false. Returns (false, false) when the key does not exist or the value cannot be converted.

xc.Set("debug", true)
d, ok := xc.GetBool("debug")    // true,  true

xc.Set("retries", 0)
r, ok := xc.GetBool("retries")  // false, true (zero int → false)

xc.Set("factor", 2.5)
f, ok := xc.GetBool("factor")   // true,  true (non-zero float → true)

func (*XConfig) GetBoolCollection

func (c *XConfig) GetBoolCollection(key string) ([]bool, bool)

GetBoolCollection returns the value of key as a []bool slice. A single bool scalar is wrapped in a one-element slice. Returns (nil, false) when the key does not exist or holds an incompatible type.

// Config file:
//   flag=true
//   flag=false
//   flag=true
flags, ok := xc.GetBoolCollection("flag")
// flags == []bool{true, false, true}, ok == true

func (*XConfig) GetCollection

func (c *XConfig) GetCollection(key string) (xcore.XDatasetCollectionDef, bool)

GetCollection returns the value of key as an xcore.XDatasetCollectionDef. Returns (nil, false) when the key does not exist or its value does not implement that interface.

func (*XConfig) GetConfig

func (c *XConfig) GetConfig(key string) *XConfig

GetConfig returns the nested sub-XConfig stored under key, or nil when the key does not exist or its value is not a *XConfig.

// Config file:
//   database.host=db.example.com
//   database.port=5432
//   database.tls=true

db := xc.GetConfig("database")
if db != nil {
    host, _ := db.GetString("host")  // "db.example.com"
    port, _ := db.GetInt("port")     // 5432
    tls,  _ := db.GetBool("tls")     // true
}

func (*XConfig) GetDataset

func (c *XConfig) GetDataset(key string) (xcore.XDatasetDef, bool)

GetDataset returns the value of key as an xcore.XDatasetDef. Only nested sub-XConfig entries satisfy this interface. Returns (nil, false) when the key does not exist or holds a scalar value.

// Config file:
//   database.host=localhost
//   database.port=5432

if ds, ok := xc.GetDataset("database"); ok {
    // ds implements xcore.XDatasetDef and can be passed to xcore templates.
    host, _ := ds.GetString("host")  // "localhost"
}

func (*XConfig) GetFloat

func (c *XConfig) GetFloat(key string) (float64, bool)

GetFloat returns the value of key as a float64. Int values are widened without loss; bool values are converted to 1.0 (true) or 0.0 (false). Returns (0, false) when the key does not exist or the value cannot be converted.

xc.Set("ratio", 3.14)
r, ok := xc.GetFloat("ratio")   // 3.14, true

xc.Set("count", 7)
n, ok := xc.GetFloat("count")   // 7.0,  true (int widened)

func (*XConfig) GetFloatCollection

func (c *XConfig) GetFloatCollection(key string) ([]float64, bool)

GetFloatCollection returns the value of key as a []float64 slice. A single float64 scalar is wrapped in a one-element slice. Returns (nil, false) when the key does not exist or holds an incompatible type.

// Config file:
//   ratio=0.25
//   ratio=0.50
//   ratio=0.75
ratios, ok := xc.GetFloatCollection("ratio")
// ratios == []float64{0.25, 0.50, 0.75}, ok == true

func (*XConfig) GetInt

func (c *XConfig) GetInt(key string) (int, bool)

GetInt returns the value of key as an int. Float64 values are truncated toward zero; bool values are converted to 1 (true) or 0 (false). Returns (0, false) when the key does not exist or the value cannot be converted.

xc.Set("workers", 4)
n, ok := xc.GetInt("workers")   // 4, true

xc.Set("ratio", 1.9)
r, ok := xc.GetInt("ratio")     // 1, true (float64 truncated toward zero)

xc.Set("enabled", true)
e, ok := xc.GetInt("enabled")   // 1, true (bool → int)

func (*XConfig) GetIntCollection

func (c *XConfig) GetIntCollection(key string) ([]int, bool)

GetIntCollection returns the value of key as a []int slice. A single int scalar is wrapped in a one-element slice. Returns (nil, false) when the key does not exist or holds an incompatible type.

// Config file:
//   port=8080
//   port=8081
//   port=8082
ports, ok := xc.GetIntCollection("port")
// ports == []int{8080, 8081, 8082}, ok == true

func (*XConfig) GetString

func (c *XConfig) GetString(key string) (string, bool)

GetString returns the value of key as a string. If the stored value is not already a string, it is converted with fmt.Sprint. Returns ("", false) when the key does not exist.

xc.Set("version", "2.3.1")
ver, ok := xc.GetString("version")   // "2.3.1", true

xc.Set("port", 8080)
port, ok := xc.GetString("port")     // "8080", true (int → string)

func (*XConfig) GetStringCollection

func (c *XConfig) GetStringCollection(key string) ([]string, bool)

GetStringCollection returns the value of key as a []string slice. A single string scalar is wrapped in a one-element slice so that callers can always range over the result without a type switch. Returns (nil, false) when the key does not exist or holds an incompatible type.

// Config file:
//   tag=stable
//   tag=canary
tags, ok := xc.GetStringCollection("tag")
// tags == []string{"stable", "canary"}, ok == true

// Single-value promotion:
xc.Set("env", "production")
envs, ok := xc.GetStringCollection("env")
// envs == []string{"production"}, ok == true

func (*XConfig) GetTime

func (c *XConfig) GetTime(key string) (time.Time, bool)

GetTime returns the value of key as a time.Time. Returns (time.Time{}, false) when the key does not exist or its value is not a time.Time.

Note: the parser does not parse dates from configuration files; time.Time values can only be stored programmatically via Set.

deadline := time.Now().Add(24 * time.Hour)
xc.Set("deadline", deadline)
t, ok := xc.GetTime("deadline")  // deadline, true

func (*XConfig) GetTimeCollection

func (c *XConfig) GetTimeCollection(key string) ([]time.Time, bool)

GetTimeCollection returns the value of key as a []time.Time slice. A single time.Time value is wrapped in a one-element slice. Returns (nil, false) when the key does not exist or holds an incompatible type.

func (*XConfig) GoString

func (c *XConfig) GoString() string

GoString returns the same content as String, prefixed with "#". It is invoked by the %#v formatting verb and by Go's default struct printer.

func (*XConfig) LoadFile

func (c *XConfig) LoadFile(filename string) error

LoadFile reads the file at filename and populates the XConfig, replacing any existing entry that shares a key with one from the file. Entries that exist in the config but are absent from the file are left untouched.

To add entries from the file without replacing existing ones, use MergeFile.

xc := xconfig.New()
if err := xc.LoadFile("/etc/myapp/app.conf"); err != nil {
    log.Fatal(err)
}
host, _ := xc.GetString("host")
port, _ := xc.GetInt("port")

LoadFile returns an error if filename contains a path-traversal sequence (".."), if the file cannot be opened, or if any line cannot be parsed.

func (*XConfig) LoadString

func (c *XConfig) LoadString(data string) error

LoadString parses the configuration text in data and replaces any existing entries that share a key with entries from data. The format is identical to a configuration file. Use MergeString to add entries without replacing existing ones.

xc := xconfig.New()
xc.LoadString("host=localhost\nport=5432\ndebug=false\n")
host, _ := xc.GetString("host")   // "localhost"
port, _ := xc.GetInt("port")      // 5432
debug, _ := xc.GetBool("debug")   // false

func (*XConfig) LoadXConfig

func (c *XConfig) LoadXConfig(data *XConfig) error

LoadXConfig copies all entries from src into c, replacing existing entries. src is deep-cloned before insertion, so subsequent modifications to either object do not affect the other. Use MergeXConfig to add entries without replacing existing ones.

LoadXConfig is a no-op when src is nil.

base := xconfig.New()
base.LoadFile("base.conf")

active := xconfig.New()
active.LoadXConfig(base)         // independent copy of base
active.Set("env", "production")  // does not affect base

func (*XConfig) Marshal added in v0.4.3

func (c *XConfig) Marshal() string

Marshal returns the complete serialised text of the XConfig in the .conf format. The output preserves comments, blank lines, and the original insertion order. It can be written to a file and reloaded with LoadFile or LoadString without any loss of data or type information.

xc := xconfig.New()
xc.Set("host", "localhost")
xc.Set("port", 5432)
fmt.Print(xc.Marshal())
// Output:
// host=localhost
// port=5432
//

String values that would be misinterpreted by the parser are automatically protected with the '"' prefix, so a round-trip is always lossless:

xc.Set("label", "true")      // string, not bool
text := xc.Marshal()         // produces: label="true
xc2 := xconfig.New()
xc2.LoadString(text)
v, _ := xc2.GetString("label")  // "true"

func (*XConfig) MergeFile

func (c *XConfig) MergeFile(filename string) error

MergeFile reads the file at filename and merges its entries into the XConfig. When a key already exists, the new value is appended to form an array; existing entries are not replaced. To replace existing entries instead, use LoadFile.

xc := xconfig.New()
xc.LoadFile("defaults.conf")
xc.MergeFile("local.conf")   // extends or supplements defaults

// Per-entry operators still take effect inside a merge:
// "host:=override.example.com" in local.conf will always replace host.

MergeFile returns an error if filename contains a path-traversal sequence, if the file cannot be opened, or if any line cannot be parsed.

func (*XConfig) MergeString

func (c *XConfig) MergeString(data string) error

MergeString parses the configuration text in data and merges its entries into the XConfig. Existing entries are extended rather than replaced.

xc := xconfig.New()
xc.LoadString("tag=stable\n")
xc.MergeString("tag=latest\n")
tags, _ := xc.GetStringCollection("tag")
// tags == []string{"stable", "latest"}

func (*XConfig) MergeXConfig

func (c *XConfig) MergeXConfig(data *XConfig) error

MergeXConfig merges all entries from src into c. Existing entries are extended rather than replaced; src is not modified.

MergeXConfig is a no-op when src is nil.

defaults := xconfig.New()
defaults.LoadFile("defaults.conf")

xc := xconfig.New()
xc.LoadFile("app.conf")
xc.MergeXConfig(defaults)   // fills in any keys absent from app.conf

func (*XConfig) SaveFile added in v0.4.3

func (c *XConfig) SaveFile(filename string) error

SaveFile serialises the XConfig and writes it to filename.

The file is written with mode 0644. Comments, blank lines, and the original insertion order are preserved. String values that would be misinterpreted by the parser on reload are automatically protected with the '"' prefix, making the save-then-load cycle lossless.

xc := xconfig.New()
xc.LoadFile("app.conf")
xc.Set("version", "1.2.3")
if err := xc.SaveFile("app.conf"); err != nil {
    log.Fatal(err)
}

SaveFile returns an error if filename contains a path-traversal sequence or if the file cannot be written.

func (*XConfig) Set

func (c *XConfig) Set(key string, value interface{})

Set creates or replaces the entry for key with value.

Accepted value types are string, int, float64, and bool. Values of any other type are stored with type code 0 and serialised via fmt.Sprint.

Dotted key paths create or update nested sub-configurations:

xc.Set("host", "db.example.com")
xc.Set("port", 5432)
xc.Set("tls", true)
xc.Set("timeout", 30.5)

// Dotted path — creates or updates a "database" sub-config:
xc.Set("database.host", "db.example.com")
xc.Set("database.port", 5432)

db := xc.GetConfig("database")
// db.GetString("host") → "db.example.com"
// db.GetInt("port")    → 5432

Set is a no-op when key is the empty string.

func (*XConfig) String

func (c *XConfig) String() string

String returns a human-readable ordered summary of the XConfig contents. Comments and blank lines are included verbatim; parameter entries are rendered as "key:value". This output is intended for debugging and logging; use Marshal or SaveFile to produce a configuration text that can be reloaded.

xc := xconfig.New()
xc.Set("host", "localhost")
xc.Set("port", 5432)
fmt.Print(xc)
// Output:
// XConfig[
// host:localhost
// port:5432
// ]

type XConfigDef

type XConfigDef interface {
	xcore.XDatasetDef
}

XConfigDef is the interface satisfied by XConfig. It extends xcore.XDatasetDef with no additional methods, providing a named type alias that callers can use to accept any XConfig-compatible value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL