ini

package module
v2.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2024 License: MIT Imports: 14 Imported by: 19

README

INI

GitHub go.mod Go version GitHub tag (latest SemVer) Coverage Status Go Report Card Unit-Tests Go Reference

INI contents parser by Golang, INI config data management.

中文说明

Features

  • Easy to use(get: Int Int64 Bool String StringMap ..., set: Set)
  • Support multi file, data load
  • Support for decode data to struct
  • Support data override merge
  • Support parse ENV variable
  • Support comments start with ; #, multi line comments /* .. */
  • Support multi line value with """ or '''
  • Complete unit test(coverage > 90%)
  • Support variable reference, default compatible with Python's configParser format %(VAR)s
Parser

Package parser is a Parser for parse INI format content to golang data

Dotenv

Package dotenv that supports importing ENV data from files (eg .env)

More formats

If you want more support for file content formats, recommended use gookit/config

  • gookit/config - Support multi formats: JSON(default), INI, YAML, TOML, HCL

GoDoc

Install

go get github.com/gookit/ini/v2

Usage

  • example data(testdata/test.ini):
# comments
name = inhere
age = 50
debug = true
hasQuota1 = 'this is val'
hasQuota2 = "this is val1"
can2arr = val0,val1,val2
shell = ${SHELL}
noEnv = ${NotExist|defValue}
nkey = val in default section

; comments
[sec1]
key = val0
some = value
stuff = things
varRef = %(nkey)s
Load data
package main

import (
	"github.com/gookit/ini/v2"
)

// go run ./examples/demo.go
func main() {
	// config, err := ini.LoadFiles("testdata/tesdt.ini")
	// LoadExists will ignore not exists file
	err := ini.LoadExists("testdata/test.ini", "not-exist.ini")
	if err != nil {
		panic(err)
	}

	// load more, will override prev data by key
	err = ini.LoadStrings(`
age = 100
[sec1]
newK = newVal
some = change val
`)
	// fmt.Printf("%v\n", config.Data())
}
Read data
  • Get integer
age := ini.Int("age")
fmt.Print(age) // 100
  • Get bool
val := ini.Bool("debug")
fmt.Print(val) // true
  • Get string
name := ini.String("name")
fmt.Print(name) // inhere
  • Get section data(string map)
val := ini.StringMap("sec1")
fmt.Println(val) 
// map[string]string{"key":"val0", "some":"change val", "stuff":"things", "newK":"newVal"}
  • Value is ENV var
value := ini.String("shell")
fmt.Printf("%q", value)  // "/bin/zsh"
  • Get value by key path
value := ini.String("sec1.key")
fmt.Print(value) // val0
  • Use var refer
value := ini.String("sec1.varRef")
fmt.Printf("%q", value) // "val in default section"
  • Set new value
// set value
ini.Set("name", "new name")
name = ini.String("name")
fmt.Printf("%q", name) // "new name"

Mapping data to struct

type User struct {
	Name string
	Age int
}

user := &User{}
ini.MapStruct(ini.DefSection(), user)

dump.P(user)

Special, mapping all data:

ini.MapStruct("", ptr)

Variable reference resolution

[portal] 
url = http://%(host)s:%(port)s/api
host = localhost 
port = 8080

If variable resolution is enabled,will parse %(host)s and replace it:

cfg := ini.New()
// enable ParseVar
cfg.WithOptions(ini.ParseVar)

fmt.Print(cfg.MustString("portal.url"))
// OUT: 
// http://localhost:8080/api 

Available options

type Options struct {
	// set to read-only mode. default False
	Readonly bool
	// parse ENV var name. default True
	ParseEnv bool
	// parse variable reference "%(varName)s". default False
	ParseVar bool

	// var left open char. default "%("
	VarOpen string
	// var right close char. default ")s"
	VarClose string

	// ignore key name case. default False
	IgnoreCase bool
	// default section name. default "__default"
	DefSection string
	// sep char for split key path. default ".", use like "section.subKey"
	SectionSep string
}

Setting options for default instance:

ini.WithOptions(ini.ParseEnv,ini.ParseVar)

Setting options with new instance:

cfg := ini.New()
cfg.WithOptions(ini.ParseEnv, ini.ParseVar, func (opts *Options) {
	opts.SectionSep = ":"
	opts.DefSection = "default"
})

Dotenv

Package dotenv that supports importing data from files (eg .env) to ENV

Usage
err := dotenv.Load("./", ".env")
// err := dotenv.LoadExists("./", ".env")

val := dotenv.Get("ENV_KEY")
// Or use 
// val := os.Getenv("ENV_KEY")

// get int value
intVal := dotenv.Int("LOG_LEVEL")

// with default value
val := dotenv.Get("ENV_KEY", "default value")

Tests

  • go tests with cover
go test ./... -cover
  • run lint by GoLint
golint ./...

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli Build CLI application, tool library, running CLI commands
  • gookit/slog Lightweight, easy to extend, configurable logging library written in Go
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More, please see https://github.com/gookit

License

MIT

Documentation

Overview

Package ini is a ini config file/data manage implement

Source code and other details for the project are available at GitHub:

https://github.com/gookit/ini

INI parser is: https://github.com/gookit/ini/parser

Example
// config, err := LoadFiles("testdata/tesdt.ini")
// LoadExists will ignore not exists file
err := ini.LoadExists("testdata/test.ini", "not-exist.ini")
if err != nil {
	panic(err)
}

config := ini.Default()

// load more, will override prev data by key
_ = config.LoadStrings(`
age = 100
[sec1]
newK = newVal
some = change val
`)
// fmt.Printf("%v\n", config.Data())

iv := config.Int("age")
fmt.Printf("get int\n - val: %v\n", iv)

bv := config.Bool("debug")
fmt.Printf("get bool\n - val: %v\n", bv)

name := config.String("name")
fmt.Printf("get string\n - val: %v\n", name)

sec1 := config.StringMap("sec1")
fmt.Printf("get section\n - val: %#v\n", sec1)

str := config.String("sec1.key")
fmt.Printf("get sub-value by path 'section.key'\n - val: %s\n", str)

// can parse env name(ParseEnv: true)
fmt.Printf("get env 'envKey' val: %s\n", config.String("shell"))
fmt.Printf("get env 'envKey1' val: %s\n", config.String("noEnv"))

// set value
_ = config.Set("name", "new name")
name = config.String("name")
fmt.Printf("set string\n - val: %v\n", name)

// export data to file
// _, err = config.WriteToFile("testdata/export.ini")
// if err != nil {
// 	panic(err)
// }

// Out:
// get int
// - val: 100
// get bool
// - val: true
// get string
// - val: inhere
// get section
// - val: map[string]string{"stuff":"things", "newK":"newVal", "key":"val0", "some":"change val"}
// get sub-value by path 'section.key'
// - val: val0
// get env 'envKey' val: /bin/zsh
// get env 'envKey1' val: defValue
// set string
// - val: new name
Output:

Index

Examples

Constants

View Source
const (
	SepSection = "."
	DefTagName = "ini"
)

some default constants

Variables

This section is empty.

Functions

func Bool

func Bool(key string, defVal ...bool) bool

Bool get a bool value, if not found return default value

func Data

func Data() map[string]Section

Data get all data from default instance

func DefSection

func DefSection() string

DefSection get default section name

func Delete

func Delete(key string) bool

Delete value by key

func Error

func Error() error

Error get

func Get

func Get(key string, defVal ...string) string

Get a value by key string. you can use '.' split for get value in a special section

func GetValue

func GetValue(key string) (string, bool)

GetValue get a value by key string. you can use '.' split for get value in a special section

func HasKey

func HasKey(key string) bool

HasKey check key exists

func IgnoreCase

func IgnoreCase(opts *Options)

IgnoreCase for get/set value by key

func Int

func Int(key string, defVal ...int) int

Int get a int by key

func Int64

func Int64(key string, defVal ...int64) int64

Int64 get a int value, if not found return default value

func IsEmpty

func IsEmpty() bool

IsEmpty config data is empty

func LoadData

func LoadData(data map[string]Section) error

LoadData load data map

func LoadExists

func LoadExists(files ...string) error

LoadExists load files, will ignore not exists

func LoadFiles

func LoadFiles(files ...string) error

LoadFiles load data from files

func LoadStrings

func LoadStrings(strings ...string) error

LoadStrings load data from strings

func MapStruct added in v2.0.6

func MapStruct(key string, ptr any) error

MapStruct get config data and binding to the structure.

func ParseEnv

func ParseEnv(opts *Options)

ParseEnv will parse ENV key on get value

Usage:

ini.NewWithOptions(ini.ParseEnv)

func ParseVar

func ParseVar(opts *Options)

ParseVar on get value

Usage:

ini.NewWithOptions(ini.ParseVar)

func Readonly

func Readonly(opts *Options)

Readonly setting

Usage:

ini.NewWithOptions(ini.Readonly)

func ReplaceNl added in v2.1.3

func ReplaceNl(opts *Options)

ReplaceNl for parse

func Reset

func Reset()

Reset all data for the default

func ResetStd added in v2.1.2

func ResetStd()

ResetStd instance

func SectionKeys added in v2.0.3

func SectionKeys(withDefSection bool) (ls []string)

SectionKeys get all section names

func Set

func Set(key string, val any, section ...string) error

Set a value to the section by key.

if section is empty, will set to default section

func String

func String(key string, defVal ...string) string

String get a string by key

func StringMap

func StringMap(name string) map[string]string

StringMap get a section data map

func Strings

func Strings(key string, sep ...string) []string

Strings get a string array, by split a string

func Uint

func Uint(key string, defVal ...uint) uint

Uint get a uint value, if not found return default value

func WithOptions

func WithOptions(opts ...func(*Options))

WithOptions apply some options

Types

type Ini

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

Ini config data manager

func Default

func Default() *Ini

Default config instance

func New

func New() *Ini

New a config instance, with default options

func NewWithOptions

func NewWithOptions(opts ...func(*Options)) *Ini

NewWithOptions new an instance and with some options

Usage:

ini.NewWithOptions(ini.ParseEnv, ini.Readonly)

func (*Ini) Bool

func (c *Ini) Bool(key string, defVal ...bool) (value bool)

Bool Looks up a value for a key in this section and attempts to parse that value as a boolean, along with a boolean result similar to a map lookup.

The `value` boolean will be false in the event that the value could not be parsed as a bool

func (*Ini) Data

func (c *Ini) Data() map[string]Section

Data get all data

func (*Ini) Decode added in v2.1.2

func (c *Ini) Decode(ptr any) error

Decode all data to struct pointer

func (*Ini) DefSection

func (c *Ini) DefSection() string

DefSection get default section name

func (*Ini) DelSection

func (c *Ini) DelSection(name string) (ok bool)

DelSection del section by name

func (*Ini) Delete

func (c *Ini) Delete(key string) (ok bool)

Delete value by key

func (*Ini) Error

func (c *Ini) Error() error

Error get

func (*Ini) Get

func (c *Ini) Get(key string, defVal ...string) string

Get a value by key string.

you can use '.' split for get value in a special section

func (*Ini) GetValue

func (c *Ini) GetValue(key string) (val string, ok bool)

GetValue a value by key string.

you can use '.' split for get value in a special section

func (*Ini) HasKey

func (c *Ini) HasKey(key string) (ok bool)

HasKey check key exists

func (*Ini) HasSection

func (c *Ini) HasSection(name string) bool

HasSection has section

func (*Ini) Int

func (c *Ini) Int(key string, defVal ...int) (value int)

Int get a int value, if not found return default value

func (*Ini) Int64

func (c *Ini) Int64(key string, defVal ...int64) (value int64)

Int64 get a int value, if not found return default value

func (*Ini) IsEmpty

func (c *Ini) IsEmpty() bool

IsEmpty config data is empty

func (*Ini) LoadData

func (c *Ini) LoadData(data map[string]Section) (err error)

LoadData load data map

func (*Ini) LoadExists

func (c *Ini) LoadExists(files ...string) (err error)

LoadExists load files, will ignore not exists

func (*Ini) LoadFiles

func (c *Ini) LoadFiles(files ...string) (err error)

LoadFiles load data from files

func (*Ini) LoadStrings

func (c *Ini) LoadStrings(strings ...string) (err error)

LoadStrings load data from strings

func (*Ini) MapStruct added in v2.0.6

func (c *Ini) MapStruct(key string, ptr any) error

MapStruct get config data and binding to the structure. If the key is empty, will bind all data to the struct ptr.

Usage:

user := &Db{}
ini.MapStruct("user", &user)

func (*Ini) MapTo deprecated added in v2.0.5

func (c *Ini) MapTo(ptr any) error

MapTo mapping all data to struct pointer.

Deprecated: please use Decode()

func (*Ini) NewSection

func (c *Ini) NewSection(name string, values map[string]string) (err error)

NewSection add new section data, existed will be replaced

func (*Ini) Options

func (c *Ini) Options() Options

Options get options info.

Notice: return is value. so, cannot change options

func (*Ini) PrettyJSON

func (c *Ini) PrettyJSON() string

PrettyJSON translate to pretty JSON string

func (*Ini) Reset

func (c *Ini) Reset()

Reset all data

func (*Ini) Section

func (c *Ini) Section(name string) Section

Section get a section data map. is alias of StringMap()

func (*Ini) SectionKeys added in v2.0.3

func (c *Ini) SectionKeys(withDefSection bool) (ls []string)

SectionKeys get all section names

func (*Ini) Set

func (c *Ini) Set(key string, val any, section ...string) (err error)

Set a value to the section by key.

if section is empty, will set to default section

func (*Ini) SetSection

func (c *Ini) SetSection(name string, values map[string]string) (err error)

SetSection if not exist, add new section. If existed, will merge to old section.

func (*Ini) String

func (c *Ini) String(key string, defVal ...string) string

String like Get method

func (*Ini) StringMap

func (c *Ini) StringMap(name string) (mp map[string]string)

StringMap get a section data map by name

func (*Ini) Strings

func (c *Ini) Strings(key string, sep ...string) (ss []string)

Strings get a string array, by split a string

func (*Ini) Uint

func (c *Ini) Uint(key string, defVal ...uint) (value uint)

Uint get a int value, if not found return default value

func (*Ini) WithOptions

func (c *Ini) WithOptions(opts ...func(*Options))

WithOptions apply some options

func (*Ini) WriteTo

func (c *Ini) WriteTo(out io.Writer) (n int64, err error)

WriteTo out an INI File representing the current state to a writer.

func (*Ini) WriteToFile

func (c *Ini) WriteToFile(file string) (int64, error)

WriteToFile write config data to a file

type Options

type Options struct {
	// Readonly set to read-only mode. default False
	Readonly bool
	// TagName for binding struct
	TagName string
	// ParseEnv parse ENV var name. default True
	ParseEnv bool
	// ParseVar parse variable reference "%(varName)s". default False
	ParseVar bool
	// ReplaceNl replace the "\n" to newline
	ReplaceNl bool

	// VarOpen var left open char. default "%("
	VarOpen string
	// VarClose var right close char. default ")s"
	VarClose string

	// IgnoreCase ignore key name case. default False
	IgnoreCase bool
	// DefSection default section name. default "__default", it's allow empty string.
	DefSection string
	// SectionSep sep char for split key path. default ".", use like "section.subKey"
	SectionSep string
}

Options for config

func GetOptions added in v2.0.3

func GetOptions() Options

GetOptions get options info.

Notice: return is value. so, cannot change Ini instance

type Section

type Section map[string]string

Section in INI config

Directories

Path Synopsis
Package dotenv provide load .env data to os ENV
Package dotenv provide load .env data to os ENV
Package parser is a Parser for parse INI format content to golang data
Package parser is a Parser for parse INI format content to golang data

Jump to

Keyboard shortcuts

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