ini

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2019 License: MIT Imports: 12 Imported by: 3 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ini

GoDoc Build Status Coverage Status Go Report Card

ini parse by golang. ini config data manage

  • Easy to use(get: Int Bool String StringMap, set: SetInt SetBool SetString ...)
  • Support multi file, data load
  • Support data override merge
  • Support parse ENV variable
  • Support variable reference, default compatible with Python's configParser format %(VAR)s
  • Complete unit test(coverage > 90%)

中文说明

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

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"
)

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

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

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
cfg := ini.New()
cfg.WithOptions(ini.ParseEnv,ini.ParseVar, func (opts *Options) {
	opts.SectionSep = ":"
	opts.DefSection = "default"
})

Tests

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

Refer

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
config, err := LoadExists("testdata/test.ini", "not-exist.ini")
if err != nil {
	panic(err)
}

// 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, ok := config.Int("age")
fmt.Printf("get int\n - ok: %v, val: %v\n", ok, iv)

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

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

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

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

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

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

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

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

Index

Examples

Constants

View Source
const (
	SepSection = "."
	DefSection = "__default"
)

some default constants

Variables

This section is empty.

Functions

func IgnoreCase added in v1.0.1

func IgnoreCase(opts *Options)

IgnoreCase for get/set value by key

func ParseEnv added in v1.0.1

func ParseEnv(opts *Options)

ParseEnv on get value usage: ini.WithOptions(ini.ParseEnv)

func ParseVar added in v1.0.8

func ParseVar(opts *Options)

ParseVar on get value usage: ini.WithOptions(ini.ParseVar)

func Readonly added in v1.0.1

func Readonly(opts *Options)

Readonly setting usage: ini.NewWithOptions(ini.Readonly)

Types

type Ini

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

Ini config data manager

func LoadExists

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

LoadExists load files, will ignore not exists

func LoadFiles

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

LoadFiles load data from files

func LoadStrings added in v1.0.1

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

LoadStrings load data from strings

func New

func New() *Ini

New a instance

func NewWithOptions

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

NewWithOptions new a instance and with some options Usage: ini.NewWithOptions(ini.ParseEnv, ini.Readonly)

func (*Ini) Bool added in v1.0.4

func (c *Ini) Bool(key string) (value bool, ok 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. of following(case insensitive):

  • true
  • false
  • yes
  • no
  • off
  • on
  • 0
  • 1

The `ok` 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) DefBool

func (c *Ini) DefBool(key string, def bool) bool

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

func (*Ini) DefInt

func (c *Ini) DefInt(key string, def int) (val int)

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

func (*Ini) DefSection added in v1.0.5

func (c *Ini) DefSection() string

DefSection get default section name

func (*Ini) DefString

func (c *Ini) DefString(key string, def string) string

DefString get a string value, if not found return default value

func (*Ini) DelSection added in v1.0.2

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

DelSection del section by name

func (*Ini) Delete added in v1.1.0

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

Delete value by key

func (*Ini) Get

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

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

func (*Ini) HasKey added in v1.0.3

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

HasKey check

func (*Ini) HasSection

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

HasSection has section

func (*Ini) Int added in v1.0.4

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

Int get a int value

func (*Ini) IsEmpty added in v1.1.0

func (c *Ini) IsEmpty() bool

IsEmpty config data is empty

func (*Ini) LoadData added in v1.0.2

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) MustBool

func (c *Ini) MustBool(key string) bool

MustBool get a string value, if not found return false

func (*Ini) MustInt

func (c *Ini) MustInt(key string) int

MustInt get a int value, if not found return 0

func (*Ini) MustMap added in v1.0.5

func (c *Ini) MustMap(name string) map[string]string

MustMap must return a string map

func (*Ini) MustString

func (c *Ini) MustString(key string) string

MustString get a string value, if not found return empty string

func (*Ini) NewSection added in v1.0.4

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

NewSection add new section data, existed will be replace

func (*Ini) Options added in v1.0.2

func (c *Ini) Options() *Options

Options get

func (*Ini) PrettyJSON added in v1.0.6

func (c *Ini) PrettyJSON() string

PrettyJSON translate to pretty JSON string

func (*Ini) Reset

func (c *Ini) Reset()

Reset all data

func (*Ini) Section added in v1.0.4

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

Section get a section data map

func (*Ini) Set

func (c *Ini) Set(key string, val interface{}, section ...string) (err error)

Set a value to the section by key. if section is empty, will set to default section

func (*Ini) SetBool

func (c *Ini) SetBool(key string, value bool, section ...string) error

SetBool set a bool by key

func (*Ini) SetInt

func (c *Ini) SetInt(key string, value int, section ...string) error

SetInt set a int by key

func (*Ini) SetSection

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

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

func (*Ini) SetString

func (c *Ini) SetString(key, val string, section ...string) error

SetString set a string by key

func (*Ini) String added in v1.0.2

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

GetString like Get method

func (*Ini) StringMap added in v1.0.4

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

StringMap get a section data map

func (*Ini) Strings added in v1.0.10

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

Strings get a string array, by split a string

func (*Ini) WithOptions added in v1.0.1

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 {
	// 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", it's allow empty string.
	DefSection string
	// sep char for split key path. default ".", use like "section.subKey"
	SectionSep string
}

Options for config

type Section

type Section map[string]string

Section in INI config

Directories

Path Synopsis
Package parser is a Parser for parse INI format content to golang data There are example data: # comments name = inhere age = 28 debug = true hasQuota1 = 'this is val' hasQuota2 = "this is val1" shell = ${SHELL} noEnv = ${NotExist|defValue} ; array in def section tags[] = a tags[] = b tags[] = c ; comments [sec1] key = val0 some = value stuff = things ; array in section types[] = x types[] = y how to use, please see examples:
Package parser is a Parser for parse INI format content to golang data There are example data: # comments name = inhere age = 28 debug = true hasQuota1 = 'this is val' hasQuota2 = "this is val1" shell = ${SHELL} noEnv = ${NotExist|defValue} ; array in def section tags[] = a tags[] = b tags[] = c ; comments [sec1] key = val0 some = value stuff = things ; array in section types[] = x types[] = y how to use, please see examples:

Jump to

Keyboard shortcuts

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