INI Profile Format Resolution in Go Language

init profile and parsing

The INI profile has three elements

  1. parameters

A configuration, such as key = value.

  1. sections

sections are a collection of parameters, which must be exclusive and enclosed in [].

sections do not have an obvious end. The beginning of one section is the end of another.


A comment referring to the INI configuration file, beginning with;

WindowStyle=DevExpress Dark Style

Resolution of init configuration file

Here we use the third-party library on GitHub (

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


The minimum requirement of Go is 1.6.

$ go get

Please add -u flag to update in the future.

Start using

We'll show you how to use it through a very simple example.

First, we need to create two files in any directory (my.ini and main.go), where we choose the / tmp/ini directory.

$ mkdir -p /tmp/ini
$ cd /tmp/ini
$ touch my.ini main.go
$ tree .
├── main.go
└── my.ini

0 directories, 2 files

Now let's edit my.ini file and enter the following (some from Grafana).

# possible values : production, development
app_mode = development

# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
data = /home/git/grafana

# Protocol (http or https)
protocol = http

# The http port  to use
http_port = 9999

# Redirect to correct domain if host header does not match domain
# Prevents DNS rebinding attacks
enforce_domain = true

Well, next we need to write the main.go file to manipulate the configuration file we just created.

package main

import (


func main() {
    cfg, err := ini.Load("my.ini")//Initialize a cfg
    if err != nil {
        fmt.Printf("Fail to read file: %v", err)

    // Typical read operation, default partition can be represented by an empty string
    fmt.Println("App Mode:", cfg.Section("").Key("app_mode").String())
    fmt.Println("Data Path:", cfg.Section("paths").Key("data").String())

    // We can do a few things to limit the candidates
    fmt.Println("Server Protocol:",
        cfg.Section("server").Key("protocol").In("http", []string{"http", "https"}))
    // If the read value is not in the candidate list, the default value provided is fallback
    fmt.Println("Email Protocol:",
        cfg.Section("server").Key("protocol").In("smtp", []string{"imap", "smtp"}))

    // Try Automatic Type Conversion
    fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("server").Key("http_port").MustInt(9999))
    fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n", cfg.Section("server").Key("enforce_domain").MustBool(false))
    // Almost. Modify a value and save it

Run the program, we can see the following output

$ go run main.go
App Mode: development
Data Path: /home/git/grafana
Server Protocol: http
Email Protocol: smtp
Port Number: (int) 9999
Enforce Domain: (bool) true

$ cat my.ini.local
# possible values : production, development
app_mode = production

# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
data = /home/git/grafana

Advanced Usage

Mapping configuration files to structures

Want to play with INI in a more object-oriented way?Good idea.

The configuration file is as follows:

Name = Unknwon
age = 21
Male = true
Born = 1993-01-01T20:17:05Z

Content = Hi is a good man!
Cities = HangZhou, Boston
//Construct the structure from the contents of the configuration file
type Note struct {
    Content string
    Cities  []string

type Person struct {
    Name string
    Age  int `ini:"age"`//Reflection is needed here because it is not the same field as the ini file
    Male bool
    Born time.Time
    Created time.Time `ini:"-"`

func main() {
    cfg, err := ini.Load("path/to/ini")
    // ...
    p := new(Person)//Initialize a structure and return a pointer to it
    err = cfg.MapTo(p)
    // ...

    // It could have been so simple.
    err = ini.MapTo(p, "path/to/ini")//Core Code
    // ...

    // Hmm-huh?Do you only need to map one partition?
    n := new(Note)
    err = cfg.Section("Note").MapTo(n)
    // ...

How do I set default values for structured fields?Simple, just assign a value to the specified field before mapping.This value does not change if the key is not found or is of the wrong type.

// ...
p := &Person{
    Name: "Joe",
// ..

Mapping Structures to Profiles

type Embeded struct {
    Dates  []time.Time `delim:"|" comment:"Time data"`
    Places []string    `ini:"places,omitempty"`
    None   []int       `ini:",omitempty"`

type Author struct {
    Name      string `ini:"NAME"`
    Male      bool
    Age       int `comment:"Author's age"`
    GPA       float64
    NeverMind string `ini:"-"`
    *Embeded `comment:"Embeded section"`

func main() {
    a := &Author{"Unknwon", true, 21, 2.8, "",
            []time.Time{time.Now(), time.Now()},
            []string{"HangZhou", "Boston"},
    cfg := ini.Empty()//Initialize an empty profile
    err = ini.ReflectFrom(cfg, a)//Core Code
    // ...

Look, a miracle has happened.

NAME = Unknwon
Male = true
; Author's age
Age = 21
GPA = 2.8

; Embeded section
; Time data
Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00
places = HangZhou,Boston


Tags: Go git github Database DNS

Posted on Mon, 04 May 2020 07:41:54 -0400 by umol