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.

  1. comments

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

[DataBase]
ServerIP=**********
ServerPort=8080
ControlConnectString=QWDJ7+XH6oWaANAGhVgh5/5UxYrA2rfz/ufAkDlN1H9Tw+v7Z0SoCfR+wYdyzCjF/ANUfPxlO6cLDAhm4xxmbADyKs6zmkWuGQNgDZmPx6c=
ControlConnectCategory=0
 
[LogonInfo]
SaveUserID=Y
UserID=admin
DBServer=AppDB
DBCenter=Demo
 
[UserConfig]
OpenDownloadFileAtOnec=Y
WindowStyle=DevExpress Dark Style
 
[Language]
Language=CHS
 
[AutoUpdate]
Version=1.1

Resolution of init configuration file

Here we use the third-party library on GitHub (https://github.com/go-ini).

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

install

The minimum requirement of Go is 1.6.

$ go get gopkg.in/ini.v1

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

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

[server]
# 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 (
    "fmt"
    "os"

    "gopkg.in/ini.v1"
)

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

    // 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
    cfg.Section("").Key("app_mode").SetValue("production")
    cfg.SaveTo("my.ini.local")
}

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

[paths]
# 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

[Note]
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
    Note
    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, "",
        &Embeded{
            []time.Time{time.Now(), time.Now()},
            []string{"HangZhou", "Boston"},
            []int{},
        }}
    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
[Embeded]
; Time data
Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00
places = HangZhou,Boston

Reference: https://ini.unknwon.cn/docs/advanced/map_and_reflect

Tags: Go git github Database DNS

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