Load A JSON Configuration From File In A Golang Application

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:

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:

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:

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 is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Amnon Baron Cohen

    it might be worth closing configFile at some point…

    • Good catch! Don’t know how I managed to forget that one 😛

      • Bernt-Johan Bergshaven

        Wouldn’t it be best to just do a defer configFile.Close() right after opening the file, just to be sure that it gets closed no matter what happens.

        I also see that you don’t catch any errors returned from JSON decoding.
        Suggested rewrite:

        func LoadConfiguration(file string) (Config, error) {
        var config Config
        configFile, err := os.Open(file)
        defer configFile.Close()
        if err != nil {
        return config, err
        }

        jsonParser := json.NewDecoder(configFile)
        err = jsonParser.Decode(&config)
        return config, err
        }

        It might be worth having a look at https://github.com/spf13/viper . This library supports JSON out of the box and has many nice features when working with config files.

  • Ddd

    Dont need declare “config” in func))

  • Amnon Baron Cohen

    try moving defer configFile.Close() to line 8?
    That way, you won’t get a panic if the os.Open() returns an error.