ini

package module
v2.0.5 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2020 License: MIT Imports: 13 Imported by: 26

README

INI

GitHub tag (latest SemVer) GoDoc Build Status Coverage Status Go Report Card

INI data parse by golang. INI config data management tool library.

中文说明

Features

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

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"
  • Setting new value
// set value
ini.Set("name", "new name")
name = ini.String("name")
fmt.Printf("%q", value) // "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 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"
})

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
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 = "."
	DefSection = "__default"
)

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 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 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 ParseEnv

func ParseEnv(opts *Options)

ParseEnv will parse ENV key on get value Usage:

ini.WithOptions(ini.ParseEnv)

func ParseVar

func ParseVar(opts *Options)

ParseVar on get value Usage:

ini.WithOptions(ini.ParseVar)

func Readonly

func Readonly(opts *Options)

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

func Reset

func Reset()

Reset all data for the default

func SectionKeys added in v2.0.3

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

SectionKeys get all section names

func Set

func Set(key string, val interface{}, 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 a 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. 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) 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) MapTo added in v2.0.5

func (c *Ini) MapTo(ptr interface{}) error

MapTo struct pointer WIP

func (*Ini) NewSection

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

NewSection add new section data, existed will be replace

func (*Ini) Options

func (c *Ini) Options() Options

Options get options info. Notice: return is value. so, cannot change Ini instance

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(withDefaultSection bool) (ls []string)

SectionKeys get all section names

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

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
	// ParseEnv parse ENV var name. default True
	ParseEnv bool
	// ParseVar parse variable reference "%(varName)s". default False
	ParseVar 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 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