confparser

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: MIT Imports: 5 Imported by: 0

README

config-file-parser-go

config-file-parser-go is a simple and lightweight Key-Value configuration file parser for Go. It easily parses simple, space-separated formats commonly found in Linux config files, making them easy to use within your Go applications.

Installation

go get github.com/ebishrimp/config-file-parser-go

Features

  • Simple: Zero external dependencies (uses only the Go standard library).
  • Lightweight: Accepts an io.Reader, ensuring a low memory footprint even when processing large files.
  • Versatile: The same key can hold both single or multiple value(s).
  • Intuitive Rules:
    • Use ParseConfig() method for parse config files.
    • Space-separated forms is allowed but, "strings with spaces" , quoted form is allowed to include spaces.
    • Only #-prefix lines will be ignored but non-prefix strings including # can be parsed as keys or values.
    • If there are grammatical error, then lines and error will return as ParseError struct.
    • Declaration of multiple values is required to written each lines.

Sample

Example of configuration

# Server settings
port 8080
debug_mode yes

# Multiple values for the same key
api_endpoint "https://primary.api.com"
api_endpoint "https://backup.api.com"

# Numeric and float values
timeout 30
ratio 0.75

sample code

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/ebishrimp/config-file-parser-go"
)

func main() {
	// 1. Open the configuration file
	file, err := os.Open("config.conf")
	if err != nil {
		log.Fatalf("failed to open file: %v", err)
	}
	defer file.Close()

	// 2. Parse the configuration
	// ParseConfig returns *ConfigurationMap and *ParseError
	conf, pErr := confparser.ParseConfig(file)
	if pErr != nil {
		// ParseError contains the line number and a detailed message
		log.Fatalf("Parse error at %v", pErr)
	}

	// 3. Get single values (String, Int, Float, Bool)
	// Bool() supports "yes/no", "y/n", and "true/false" (case-insensitive)
	port, _ := conf.Int("port")
	debug, _ := conf.Bool("debug_mode")

	fmt.Printf("Server running on port: %d (Debug: %v)\n", port, debug)

	// 4. Get multiple values (StringSlice, IntSlice, etc.)
	endpoints := conf.StringSlice("api_endpoint")
	fmt.Printf("Found %d endpoints:\n", len(endpoints))
	for i, url := range endpoints {
		fmt.Printf("  [%d] %s\n", i, url)
	}

	// 5. Check existence and count of values
	if conf.Exists("timeout") {
		t, _ := conf.Int("timeout")
		fmt.Printf("Timeout: %v seconds\n", t)
	}

	if count, err := conf.Length("api_endpoint"); err == nil {
		fmt.Printf("Total api_endpoint entries: %d\n", count)
	}
}

This code is generated by gemini.

Legacy version

Features

  • Simple: Zero external dependencies (uses only the Go standard library).
  • Lightweight: Accepts an io.Reader, ensuring a low memory footprint even when processing large files.
  • Intuitive Rules:
    • Use Parse() method.
    • Parses space- or tab-separated entries (e.g., key value).
    • Ignores anything after a # as a comment.
    • Safely skips empty lines and lines with three or more elements (e.g., key value1 value2) as invalid formats.
  • Multiple Values:
    • Use ParseMultipleValues() method
    • All values are stored into slices

Sample

Usage

  1. Prepare a Configuration File Create a config file (e.g., config.conf) that you want to parse.
# Example of config.conf
port 8080
host localhost

# Lines with 3 or more elements will be ignored
invalid_key too many values
# Example of config.conf which can be parsed by ParseMultipleValues(r io.Reader)
# The same key can hold multiple values
multiplevalues value1
multiplevalues value2

# Simultaneous description of values will be ignored
invalid_form value3 value4 value5
  1. Use in Your Go Code You can parse directly from a file or a string, as long as it satisfies the io.Reader interface.
package main

import (
	"fmt"
	"log"
	"os"

	confparser "github.com/ebishrimp/config-file-parser-go"
)

func main() {
	// 1. Open the file (you can also pass a string using strings.NewReader)
	f, err := os.Open("config.conf")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	// 2. Parse the configuration
	conf, err := confparser.Parse(f)
	if err != nil {
		log.Fatalf("Parse error: %v", err)
	}

	// 3. Retrieve values

	// Get as a string
	host := conf.GetValue("host")
	fmt.Printf("Host: %s\n", host)

	// Get as an integer
	port, err := conf.IntGetValue("port")
	if err != nil {
		log.Printf("Failed to get port: %v", err)
	} else {
		fmt.Printf("Port: %d\n", port)
	}

	// Check if a key exists
	if conf.ExistsValue("invalid_key") {
		fmt.Println("invalid_key exists")
	} else {
		fmt.Println("invalid_key does not exist because it was skipped")
	}

	// 4. Parse multiple values
	multiConf, err := confparser.ParseMultipleValues(f)
	if err != nil {
		log.Fatalf("Parse error: %v", err)
	}

	// 5. Retrieve values

	// Get string slice
	multival := multiConf.GetMultipleValues("multiplevalues")
	// multival[0] == "value1"
	// multival[1] == "value2"

	// Get a first contest of slice
	firstval := multiConf.GetFirstValue("multiplevalues")
	// firstval == "value1"

	// Check if a key exists
	if conf.ExistsMultipleValues("invalid_form") {
		fmt.Println("invalid_form exists")
	} else {
		fmt.Println("invalid_form does not exist because it was skipped")
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseConfig added in v1.1.0

func ParseConfig(r io.Reader) (*ConfigurationMap, *ParseError)

Read and parse the configuration through the io.Reader, return a ConfigurationMap struct. If there is an error during reading, return a ParseError struct which contains the line number and the error message. The ConfigurationMap struct should support multiple values for the same key.

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

func Parse

func Parse(r io.Reader) (*Config, error)

read and parse the configuration from the reader, return a Config struct, if there is an error during reading, return an error

func (*Config) ExistsValue

func (c *Config) ExistsValue(key string) bool

return true if the key exists, otherwise return false

func (*Config) GetValue

func (c *Config) GetValue(key string) string

return value which is associated with the key, if the key does not exist, return empty string

func (*Config) IntGetValue

func (c *Config) IntGetValue(key string) (int, error)

return value which is assocated with key and is converted to int, if the key does not exist or the value cannot be converted to int, return error

type ConfigurationMap added in v1.1.0

type ConfigurationMap struct {
	// contains filtered or unexported fields
}

Recommended to use ConfigurationMap instead of MultiConfig or Config. The ConfigurationMap struct has unified functions to get value, get multiple values, check if key exists, and it can handle both single and multiple values for the same key.

func (ConfigurationMap) Bool added in v1.1.0

func (c ConfigurationMap) Bool(key string) (bool, error)

Return the value which is associated with the key and is converted to bool, if the key does not exist or the value cannot be converted to bool, return error. Multiple values for the same key are not allowed for boolean values, if there are multiple values, return error.

func (*ConfigurationMap) Exists added in v1.1.0

func (c *ConfigurationMap) Exists(key string) bool

Return true if the key exists, otherwise return false

func (*ConfigurationMap) Float added in v1.1.0

func (c *ConfigurationMap) Float(key string) (float64, error)

Return the value which is associated with the key and is converted to float, if the key does not exist or the value cannot be converted to float, return error. If there are multiple values for the same key, return the first value.

func (*ConfigurationMap) FloatSlice added in v1.1.0

func (c *ConfigurationMap) FloatSlice(key string) ([]float64, error)

Return a slice of floats which are associated with the key, if the key does not exist, return an empty slice. If there is an error, return an error.

func (*ConfigurationMap) Int added in v1.1.0

func (c *ConfigurationMap) Int(key string) (int, error)

Return the value which is associated with the key and is converted to int, if the key does not exist or the value cannot be converted to int, return error. If there are multiple values for the same key, return the first value.

func (*ConfigurationMap) IntSlice added in v1.1.0

func (c *ConfigurationMap) IntSlice(key string) ([]int, error)

Return a slice of integers which are associated with the key, if the key does not exist, return an empty slice.

func (*ConfigurationMap) Length added in v1.1.0

func (c *ConfigurationMap) Length(key string) (int, error)

Return the number of values which are associated with the key, if the key does not exist, return 0. If there is an error, return an error.

func (*ConfigurationMap) String added in v1.1.0

func (c *ConfigurationMap) String(key string) string

Return the value which is associated with the key, if the key does not exist, return empty string. If there are multiple values for the same key, return the first value.

func (*ConfigurationMap) StringSlice added in v1.1.0

func (c *ConfigurationMap) StringSlice(key string) []string

Return a slice of strings which are associated with the key, if the key does not exist, return an empty slice

type MultiConfig added in v1.0.0

type MultiConfig struct {
	// contains filtered or unexported fields
}

func ParseMultipleValues added in v1.0.0

func ParseMultipleValues(r io.Reader) (*MultiConfig, error)

read and parse the configuration from the reader, return a MultiConfig struct, if there is an error during reading, return an error. The MultiConfig struct should support multiple values for the same key, and the values should be stored in a slice of strings.

func (*MultiConfig) ExistsMultipleValues added in v1.0.1

func (c *MultiConfig) ExistsMultipleValues(key string) bool

return true if the key exists, otherwise return false

func (*MultiConfig) GetFirstValue added in v1.0.1

func (c *MultiConfig) GetFirstValue(key string) string

return the first value which is associated with the key, if the key does not exist, return empty string

func (*MultiConfig) GetMultipleValues added in v1.0.1

func (c *MultiConfig) GetMultipleValues(key string) []string

return a slice of strings which are associated with the key, if the key does not exist, return an empty slice

type ParseError added in v1.1.0

type ParseError struct {
	// contains filtered or unexported fields
}

func (*ParseError) Error added in v1.1.0

func (err *ParseError) Error() string

Jump to

Keyboard shortcuts

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