Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Load A JSON Configuration From File In A Golang Application

TwitterFacebookRedditLinkedInHacker News

Have you ever built an application and decided that you didn’t want to hardcode a bunch of values that might change frequently? The answer is, probably yes. When building a web application, it is common to separate configuration details into a separate file which might contain database information, hostnames, passwords, and anything else that probably shouldn’t exist in the application as hard-coded values.

We’re going to see how to open a JSON configuration file using the Go programming language and load it into a custom data structure to be used throughout the application.

There isn’t a whole lot to this because Golang makes it very easy for us. Let’s think about the data structure we want to use within the application that represents the configuration data:

type Config struct {
    Database struct {
        Host     string `json:"host"`
        Password string `json:"password"`
    } `json:"database"`
    Host string `json:"host"`
    Port string `json:"port"`
}

The above structure has a nested structure and each property, including the nested structure, has a JSON annotation. This means that the JSON equivalent to this structure would look like the following:

{
    "database": {
        "host": "localhost",
        "password": "12345"
    },
    "host": "localhost",
    "port": "8080"
}

Now say we have the above JSON data in a file called config.json and we want to load it. Using the following commands we are able to load that file and JSON decode it:

func LoadConfiguration(file string) Config {
    var config Config
    configFile, err := os.Open(file)
    defer configFile.Close()
    if err != nil {
        fmt.Println(err.Error())
    }
    jsonParser := json.NewDecoder(configFile)
    jsonParser.Decode(&config)
    return config
}

At this point the properties of the configuration file can be used throughout the Golang application. The steps to make this possible were very short and very easy, yet add huge convenience to the application development process.

A video version of this article can be found below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.