Go component learning: how to read ini configuration file


All code samples are saved in. Welcome to star: https://github.com/EnochZg/golang-examples

Installation components

go get gopkg.in/ini.v1


First create the configuration file of ini suffix config.ini take as an example

Username = pingya

Add the following code to the main function to read the username configuration

package main

import (

func main() {
	cfg, err := ini.Load("config.ini")
	if err != nil {
		fmt.Println ("file read error", ERR)

After running, you can read the value of username. What is the role of section above? We add the following configuration to the configuration file

username = root

At this time, there are two identical usernames in the configuration file. Which one should prevail when reading? This needs to be distinguished by section. Add the following code to the main function, and read the configuration in MySQL by passing in parameters in section


Running can find that the content read is root


Limit value

We can also limit the value. If we only allow the value of Zhang San or Li Si, if the name set by the user is not in these two, it will be Zhang San by default. The code can be written as follows

fmt.Println ( cfg.Section ("MySQL"). Key ("username"). In ("Zhang San", [] string {"Zhang San", "Li Si"}))

After running, the output result is “Zhang San”

Modify configuration file

Add the following code to the main line number to set it back to the configuration file

cfg.Section ("MySQL"). Key ("username"). SetValue ("Li Si")
err = cfg.SaveTo("config.ini")
if err != nil {
	fmt.Println (file save error, ERR)

The above code means to change the user name in MySQL to Li Si. Let’s check it out config.ini , successfully changed to Li Si

User name = Li Si

Recommended Today

Another onedrive command line client

Another onedrive command line client be based onLaravel-ZeroAnd made a lot of changes. This project refers toonedrivecmdBut the language is based on PHP, which is the best language in the world after all. Olaindex-cmd is the command line version of olandex Github Project address:https://github.com/WangNingkai/OLAINDEX-CMD characteristic Support directory and file listing by address or ID; Independent […]