The Ops Community

Neo
Neo

Posted on

Devops and Golang

Configuration files play an important role in the application development lifecycle. We build and deploy applications onto multiple environments and each of them must require a certain set of configurations to run.

Running applications on multiple environments require configuration to be set properly.

Golang builds a single binary of the whole application which can be run on the specific environment be it a linux binary or a windows binary.

With the release of Golang v1.16 Embed feature was also released and with that we can mount the config files onto a structure in our program while building the binary itself and we do not need to ship the configuration files explicitly.

Read configuration files

The below snippet can help you read the configuration file using the embed package.

Application Structure
image

config.yaml

name: Test_User
age: 73
Enter fullscreen mode Exit fullscreen mode

main.go

pacakge main

import (
    ...
    <imports>
)

//go:embed config.yaml
var config embed.FS

type Conf struct {
    Name string `yaml:"name"`
    Age  int    `yaml:"name"`
}

func main() {
    var configs Conf
    configs.readConfig()
    fmt.Println(configs)
}

func (conf *Conf) readConfig() *Conf {
    yamlFile, err := config.ReadFile("config.yaml")
    if err != nil {
        log.Fatalln(err)
    }
    err = yaml.Unmarshal(yamlFile, &conf)
    if err != nil {
        log.Fatalln(err)
    }
    return conf
}
Enter fullscreen mode Exit fullscreen mode

Build the binary and we don't need to worry about shipping the config.yaml while deploying our applications on any platform.

Discussion (0)