Package ini provides INI file read and write functionality in Go.

INI

GitHub Workflow Status codecov GoDoc Sourcegraph

Package ini provides INI file read and write functionality in Go.

Features

  • Load from multiple data sources(file, []byte, io.Reader and io.ReadCloser) with overwrites.
  • Read with recursion values.
  • Read with parent-child sections.
  • Read with auto-increment key names.
  • Read with multiple-line values.
  • Read with tons of helper methods.
  • Read and convert values to Go types.
  • Read and WRITE comments of sections and keys.
  • Manipulate sections, keys and comments with ease.
  • Keep sections and keys in order as you parse and save.

Installation

The minimum requirement of Go is 1.6.

$ go get gopkg.in/ini.v1

Please add -u flag to update in the future.

Getting Help

License

This project is under Apache v2 License. See the LICENSE file for the full license text.

Owner
INI
A fantastic package for INI manipulations in Go
INI
Comments
  • how will goini handle sections with the same name

    how will goini handle sections with the same name

    type Note struct { Typ string //ini:"type" Content string Cities []string Number [] int }

    [Note] typ = normal Content = Hi is a good man! Cities = HangZhou, Boston number=1,2 number=3,4

    cfg, err := ini.InsensitiveLoad("./test.ini") p := new(Note) err = cfg.MapTo(p) according to my test, 3,4 will replace 1,2 If I want to cat 3,4 to 1,2 what should I do

  • The key contains

    The key contains ":" to create ini file will add "`" before and after the key ?

    Please give general description of the problem

    when the key has ":" , such like this "s3:125244888:lewzyluyfb111" the lib function to create ini file will contains "" lead to the result is "s3:125244888:lewzyluyfb111` " , it there any solution to this problem to create normal ini file?

  • file: support non-unique sections

    file: support non-unique sections

    First of all: this is not finished yet. It fixes https://github.com/go-ini/ini/issues/190

    As there seem to be some more people now who need this, I would like to continue the work now.

    I create this PR because I need some feedback if it is ok how I implement it.

    Currently I have implemented ini.LoadSources(), f.WriteTo(), f.DeleteSpecificSection(), ini.MapTo(), f.Section("Peer").MapTo()

    What problem should be fixed?

    Wireguard has ini files like this:

    [Interface]
    Address = 192.168.2.1
    PrivateKey = <server's privatekey>
    ListenPort = 51820
    
    [Peer]
    PublicKey = <client's publickey>
    AllowedIPs = 192.168.2.2/32
    
    [Peer]
    PublicKey = <client2's publickey>
    AllowedIPs = 192.168.2.3/32
    

    And there can be unlimited [Peer] sections.

    These non unique sections are currently not supported.

    Have you added test cases to catch the problem?

    Yes, for all cases I have currently implemented. There are still cases missing to implement and to write tests for.

  • Panic when submitting non-existing files to Load()

    Panic when submitting non-existing files to Load()

    Hi,

    I'm submitting a slice of three files to ini.Load():

    cfg, err := ini.Load("/etc/securepass.conf", "/usr/local/etc/securepass.conf", "securepass.conf")
    

    Only the latter exists and has the correct permissions set. Likewise the Python ConfigParser module, it would be great if the function could read the configuration from only those accessible or return an empty configuration if no existing files were provided.

    $ ~/go/src/github.com/garlsecurity/go-securepass$ go run spctl/main.go 
    panic: runtime error: invalid memory address or nil pointer dereference
    [signal 0xb code=0x1 addr=0x0 pc=0x4811b2]
    
    goroutine 1 [running]:
    gopkg.in/ini%2ev1.(*File).GetSection(0x0, 0x7fa130, 0x7, 0x0, 0x0, 0x0)
        /home/SMARTODDS/tregliaa/go/src/gopkg.in/ini.v1/ini.go:976 +0x72
    main.loadConfiguration()
        /home/SMARTODDS/tregliaa/go/src/github.com/garlsecurity/go-securepass/spctl/main.go:50 +0xc2
    main.main()
        /home/SMARTODDS/tregliaa/go/src/github.com/garlsecurity/go-securepass/spctl/main.go:60 +0x1c
    
    goroutine 17 [syscall, locked to thread]:
    runtime.goexit()
        /usr/local/go/src/runtime/asm_amd64.s:1721 +0x1
    exit status 2
    

    Thanks for considering.

  • Support for

    Support for "ReflectFrom" to structs with fields of type map[string]TYPE

    Please give general description of the problem

    The ReflectFrom function fails to reflect to types with fields of type map[string]TYPE.

    Please provide code snippets to reproduce the problem described above

    Suppose the following INI:

    FirstName = Andrew
    
    [Employer "VMware"]
    Title = Staff II Engineer
    
    [Employer "EMC"]
    Title = Consultant Engineer
    

    and the following struct:

    type Employer struct {
        Title string
    }
    
    type Person struct {
        FirstName string
        Employer map[string]*Employer
    }
    

    The ReflectFrom function will balk with an error that type map[string]*Employer is not supported.

    It would really be great to support this as the gopkg.in/gcfg.v1 package supports unmarshalling data from INI configurations with this notation, but does not support marshaling back to INI at all. I had planned to use gcfg for backwards-compatibility in the Kubernetes Cluster API provider and cloud controller managers for vSphere and then this package for marshaling structs back to INI.

    Please see this test file for examples.

    FWIW, I really want to use this package. I even document such in the work-in-progress branch for the cluster API provider. But this feature is a deal-breaker unfortunately.

    Thanks!

    Do you have any suggestion to fix the problem?

  • Exclude not parsed values from lists.

    Exclude not parsed values from lists.

    I found that methods that return lists (Float64s, Ints, Int64s and etc.) do not handle parsing errors. For example, following code:

    config, _ := Load([]byte(_CONF_DATA))
    stringKey := config.Section("array").Key("STRINGS")
    fmt.Printf("string values: %v\n", stringKey.Strings(","))
    fmt.Printf("float values: %v\n", stringKey.Float64s(","))
    

    gives such result:

    string values: [en zh de]
    float values: [0 0 0]
    

    I think that the best solution would be to return error from these methods, but it will break down back compatibility of interface. Therefore I propose do not append to list such values, that was parsed with error.

  • all: rewrite tests to use testify instead of goconvey

    all: rewrite tests to use testify instead of goconvey

    What problem should be fixed?

    Fixes #295

    Have you added test cases to catch the problem?

    This PR is about refactoring tests, no additional tests are necessary.

    Notes for reviewer

    This is an attempt to refactor tests into using testify instead of goconvey.

    During the refactor I followed the following rules:

    • Singular top level Convey was removed everywhere
    • Multiple Convey blocks were converted into subtests (t.Run)
    • Child Convey blocks were converted into subtests (t.Run)
    • require was used everywhere when the following assertions depended on the outcome (eg. no error or no nil return value)
    • assert was used everywhere else

    I suggest turning off showing whitespaces in the diff because there are lots of indentation changes.

    If you like the result, I can refactor the remaining tests as well.

  • Large python style multiline value fix

    Large python style multiline value fix

    What problem should be fixed?

    This change

    • fixes issue #205
    • supports large values (>4kB)
    • allows to configure the maximum supported value size
    • allows to turn on debug output to figure out why a multiline value does not parse correctly

    Have you added test cases to catch the problem?

    There is a new test file with test cases as well as a test data file to cover empty lines in Python-style multiline values.

  • Unescape comment symbols in value

    Unescape comment symbols in value

    Please give general description of the problem

    As per ini file format \; should be treated as ; when parsing

    Please provide code snippets to reproduce the problem described above

    key = `test value <span style="color: %s; background: %s">more text</span>`
    

    This value in crowdin is treated test value <span style="color: %s and after ; it treats as comment

    Do you have any suggestion to fix the problem?

    Add support for adding \; that would be parsed as ; in value

  • Able to get child sections

    Able to get child sections

    for example:

    [node]
    ...
    [node.biz1]
    ...
    [node.biz2]
    ...
    [node.biz3]
    ...
    [node.bizN]
    ...
    

    in this situation, we are not sure that how many child sections will appear, child section names dont even have a pattern. so if we can do getSectionWildcard("node.*") or something like that, it will be very handy for this situation.

    thanks for your great work!

  • Map shadow key to structure

    Map shadow key to structure

    since go-ini already support {AllowShadows: true} I wish to could map to structure directly example {AllowShadows: true} [Note] typ = normal Number=1,2 Number=3,4

    Number = []string{"1,2","3,4"} or Number = []string{"1","2","3","4"} I could accept these 2 above

  •  character not escaped properly

    "=" character not escaped properly

    Version

    go1.19.3 linux/amd64

    Describe the bug

    If a value contains the "=" character, the library will write it to the output file without escaping it. This causes PHP to fail when attempting to load the .ini file with the error PHP Warning: syntax error, unexpected '=' in test.ini on line 27

    To reproduce

    writeini.go:

    package main
    
    import (
    	"github.com/go-ini/ini"
    )
    
    func main() {
    	f := ini.Empty()
    
    	test, _ := f.NewSection("test")
    	_, _ = test.NewKey("test", "=")
    
    	_ = f.SaveTo("./test.ini")
    }
    

    testini.php:

    <?php
    $ini_array = parse_ini_file("test.ini", true);
    print_r($ini_array);
    
    $ go run writeini.go
    $ php testini.php   
    PHP Warning:  syntax error, unexpected '=' in test.ini on line 2
     in ~/testini.php on line 2
    

    Expected behavior

    The library should wrap values with = characters in quotes, like it does for other characters

    Additional context

    No response

    Code of Conduct

    • [X] I agree to follow this project's Code of Conduct
  • add NoMultiLineSurroundingQuotes option

    add NoMultiLineSurroundingQuotes option

    Describe the pull request

    Consider the following multi-line ini file:

    value1 = some text here
    	some more text here 2
    

    Run the following code:

    path := "multiline_eof.ini"
    f, _ := ini.LoadSources(ini.LoadOptions{
      AllowPythonMultilineValues: true,
    }, path)
    
    f.Section("").Key("value1").SetValue("some text here\n\tsome more text here 2")
    f.SaveTo(path)
    

    Will output:

    value1 = """some text here
    	some more text here 2"""
    

    Now run:

    path := "multiline_eof.ini"
    f, _ := ini.LoadSources(ini.LoadOptions{
      AllowPythonMultilineValues: true,
      NoMultiLineSurroundingQuotes: true,
    }, path)
    
    f.Section("").Key("value1").SetValue("some text here\n\tsome more text here 2")
    f.SaveTo(path)
    

    The output is the same as the original file

    value1 = some text here
    	some more text here 2
    

    Link to the issue: n/a

    Checklist

    • [*] I agree to follow the Code of Conduct by submitting this pull request.
    • [*] I have read and acknowledge the Contributing guide.
    • [*] I have added test cases to cover the new code.
  • If the configuration item of my ini configuration file contains #, it will cause an error in reading the configuration.

    If the configuration item of my ini configuration file contains #, it will cause an error in reading the configuration.

    Version

    1.67.0

    Describe the bug

    If the configuration item of my ini configuration file contains #, it will cause the configuration to be read incorrectly. For example, my MySQL password is "xxx#123", and the obtained parameter is "xxx".

    To reproduce

    ini file

    [database] DbPassWord = "XXX#123"

    config.go

    file, err := ini.Load("config/app.ini") DbPassWord = file.Section("database").Key("DbPassWord").MustString("") fmt.Println("passwd:"DbPassWord)

    This outputs passwd: "XXX

    Expected behavior

    Configuration items containing # can be read correctly.

    Additional context

    No response

    Code of Conduct

    • [X] I agree to follow this project's Code of Conduct
  • Allow NonUniqueSections not working for Embedded Structs

    Allow NonUniqueSections not working for Embedded Structs

    Version

    v1.67.0

    Describe the bug

    When attempting to create an ini file from a struct containing a slice field, whereby

    1. the type of the slice contains an embedded struct
    2. the elements of the slice are supposed to be displayed as non-unique sections in the ini file

    the elements of the slice are correctly shown as separate sections. However, the embedded struct is only shown once; the embedded struct of the last element is written to the first section.

    To reproduce

    type BaseSlot struct {
    	Id int `ini:",nonunique"`
    }
    
    type BigSlot struct {
    	*BaseSlot `ini:"big_slot,nonunique"`
    	Color     string
    }
    
    type IniFile struct {
    	BigSlots []BigSlot `ini:"big_slot,nonunique"`
    }
    
    func main() {
    	iniFile := &IniFile{
    		BigSlots: []BigSlot{
    			{
    				BaseSlot: &BaseSlot{
    					Id: 3,
    				},
    				Color: "blue",
    			},
    			{
    				BaseSlot: &BaseSlot{
    					Id: 4,
    				},
    				Color: "red",
    			},
    		},
    	}
    
    	cfg := ini.Empty(ini.LoadOptions{
    		AllowNonUniqueSections: true,
    	})
    	err := ini.ReflectFrom(cfg, iniFile)
    	if err != nil {
    		panic(err)
    	}
    	cfg.SaveTo("./some_file.ini")
    }
    

    the resulting file looks like this:

    [big_slot]
    Id    = 4
    Color = blue
    
    [big_slot]
    Color = red
    
    

    Expected behavior

    The file to look as follows:

    [big_slot]
    Id    = 3
    Color = blue
    
    [big_slot]
    Id    = 4
    Color = red
    

    Additional context

    No response

    Code of Conduct

    • [X] I agree to follow this project's Code of Conduct
  • Fix value format when SpaceBeforeInlineComment:true

    Fix value format when SpaceBeforeInlineComment:true

    Hello,

    Would you be interested in that patch ?

    Setting the a#b value when SpaceBeforeInlineComment is true should not quote the value.

    Thank you for your work.

  • Reflect From Struct - section name configuration for root level properties

    Reflect From Struct - section name configuration for root level properties

    Describe the feature

    Let me configure dedicated section for each structure's root level property. Currently all root level properties goes into 'DEFAULT' section.

    Describe the solution you'd like

    type SampleStruct struct {
      Property1      string `ini:"section1#prop1"`
      Property2      string `ini:"section2#prop2"`
    }
    
    input := SampleStruct{
      Property1: "value1",
      Property2: "value2",
    }
    
    file := ini.Empty()
    ini.ReflectFrom(file, &input)
    cfg.WriteTo(os.Stdout)
    

    Would generate:

    [section1]
    prop1: value1
    
    [section2]
    prop2: value2
    

    Describe alternatives you've considered

    type SampleStruct struct {
      Property1      string `ini:"prop1" section:"section1"`
      Property2      string `ini:"prop2" section:"section2"`
    }
    

    Additional context

    No response

    Code of Conduct

    • [X] I agree to follow this project's Code of Conduct
A simple INI file parser and builder.

ini A simple INI file parser and builder. What Read INI files, or build them section by section. Datatypes are kept very simple. The main fuctions are

Nov 20, 2021
Gonfigure - Read and write config files in go

Gonfigure Reads ini files in golang. Reading INI Files Load file File can be loa

Jan 27, 2022
A golang package for parsing ini-style configuration files

Mini Mini is a simple ini configuration file parser. The ini syntax supported includes: The standard name=value Comments on new lines starting with #

Jan 7, 2023
ini parser for golang
ini parser for golang

INI Parser & Write Library ini parser and write library for Golang,easy-use,fast Features Can be read by []byte Can be read by file Supports file moni

Dec 3, 2022
Tinyini - Bare-bones Go library for reading INI-like configuration files

tinyini tinyini is a minimalistic library for parsing INI-like configuration files. example configuration file globalkey = globalvalue [section] key

Jan 10, 2022
INI Loader written in Go

go-ini INI Loader written in Go Single threaded & simple Examples Read all params func (app MyApp) onParam(name string, value string) bool { app.c

Feb 11, 2022
Genv is a library for Go (golang) that makes it easy to read and use environment variables in your projects. It also allows environment variables to be loaded from the .env file.

genv Genv is a library for Go (golang) that makes it easy to read and use environment variables in your projects. It also allows environment variables

Dec 21, 2022
Read files into environment variables and execute command

read-file-to-env -- Read files into environment variables and execute command Example use: read-file-to-env -one-line=HOST=/etc/hostname sh -c 'echo h

Nov 12, 2021
Small library to read your configuration from environment variables

envconfig envconfig is a library which allows you to parse your configuration from environment variables and fill an arbitrary struct. See the example

Nov 3, 2022
Quickly read variables from environment files

go-quick-env Quickly read variables from environment files The best way to import environment variables to your code, is by using .env files. This lib

May 11, 2021
goconfig uses a struct as input and populates the fields of this struct with parameters from command line, environment variables and configuration file.

goconfig goconfig uses a struct as input and populates the fields of this struct with parameters from command line, environment variables and configur

Dec 15, 2022
Light weight, extensible configuration management library for Go. Built in support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.
Light weight, extensible configuration management library for Go. Built in support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.

koanf (pronounced conf; a play on the Japanese Koan) is a library for reading configuration from different sources in different formats in Go applicat

Jan 8, 2023
It syncronizes the configuration described in a YAML file against your GitHub Organization

It syncronizes the configuration described in a YAML file against your GitHub Organization. Combined with a CI system, it can be used to implement GitOps for GitHub.

Jul 19, 2021
Little Go tool to infer an uncrustify config file from an expected format

uncrustify-infer Little Go tool to infer an uncrustify config file from an expected format Install This tool relies on an uncrustify executable, you m

Oct 8, 2021
A viewer for creating a one-page app that renders the config file as a webpage.

Matterbridge Config Viewer A viewer for creating a one-page app that renders the config file as a webpage. Local Development npm install npm run-scrip

Jul 9, 2021
App that generates a Matterbridge config file based on channel names.

Matterbridge Auto-Config App that generates a Matterbridge config file based on channel names. This remote configuration file* is generated based on s

Oct 15, 2022
formicidate is a small tool for Go application can update the value of environment variables in a .env file with code

formicidae Update .env files in Go with code. What is fomicidae? formicidate is a small tool for Go application. You can update the value of environme

Jan 23, 2022
A Go (golang) environment loader (which loads env vars from a .env file)

A Go (golang) environment loader (which loads env vars from a .env file)

Feb 8, 2022
Lightweight package that makes easier and safer to deal with environment variables.

Envisage A lightweight package that makes easier and safer to deal with environment variables. Example Try it on On GoPlay https://goplay.tools/snippe

Apr 11, 2022