Reading from and Writing to Toml Config file in Go (Golang)

When we develop golang applications, sometimes we need reading from config files. Your program has many options, and you don’t want to set every option using command line parameter. So we can use happily config files.

What format should we use (json, yaml, ini, toml)? Nowadays I prefer toml format for config files.

Toml

TOML is a file format, very easy to read and write, perfect for config files. It aims to be a minimal configuration file format that’s easy to read due to obvious semantics. It is designed to map unambiguously to a hash table. The config file should be easy to parse into data structures in a wide variety of languages. It supports comments and also does not care about indentations and spaces

sample file (config.toml):

# This is a TOML document.

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00 # First class dates

[database]
server = "192.168.1.1"
user = "test"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true

To read from the config file, there exist multiple libraries. I prefer using the Viper library.

About Viper

Viper is a complete configuration solution for Go applications. It is designed to work within an application and can handle all types of configuration needs and formats. It supports reading from yaml, json and toml files. Can set default values.

Reading from config file:
viper.SetConfigName("config") // name of config file (without extension)
viper.AddConfigPath(".")      // optionally look for config in the working directory
err := viper.ReadInConfig()   // Find and read the config file

if err != nil { // Handle errors reading the config file
  panic(fmt.Errorf("Fatal error config file: %s \n", err))
}

fmt.Println("owner name", viper.GetString("owner.name")
fmt.Println("database user", viper.GetString("database.user")

In my application, there is a requirement that a user can also change the config values. Using SQLite could be overkill. But viper currently does not support writing to the config file. Fortunately, there is a fork, which provides us the necessary functionality (WriteConfig).

viper.Set("database.user", "newuser")
viper.Set("owner.name", "John")

viper.WriteConfig()

Now your config file is changed.

The viper fork: https://github.com/theherk/viper

 

Yorum bırakın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir