Configuring Go application
Reading configuration from file
In this example, the applicaiton configuration consists of two settings. Internally, the configuration is stored in a struct of type Configuration
.
type Configuration struct {
Setting1 string
Setting2 string
}
Configuration values are read from the configuration.json
file.
{
"setting1": "setting1_value",
"setting2": "setting2_value"
}
The first step in reading the configuration from file is to declare a variable of type Configuration
.
var configuration Configuration
Next, we open the configuration.json
file. We defer the file closure, meaning that the file is to be closed at the end of the current function.
file, err := os.Open("./configuration.json")
if err != nil {
log.Fatalf("error opening configuration file: %v", err)
}
defer file.Close()
Actual configuration file reading consists of creating a new decoder using json.NewDecoder
function and then reading the file content into the configuration
variable of type Configuration
.
decoder := json.NewDecoder(file)
if err := decoder.Decode(&configuration); err != nil {
log.Fatalf("error fetching configuration from the given file: %v", err)
}
Now, if we print out the configuration
variable value, we can see that it has been populated with the settings values taken from the configuration.json
file.
fmt.Printf("Configuration: %q\n", configuration)
You can find the example full listing below.
import (
"encoding/json"
"fmt"
"log"
"os"
)
type Configuration struct {
Setting1 string
Setting2 string
}
func main() {
var configuration Configuration
file, err := os.Open("./configuration.json")
if err != nil {
log.Fatalf("error opening configuration file: %v", err)
}
defer file.Close()
decoder := json.NewDecoder(file)
if err := decoder.Decode(&configuration); err != nil {
log.Fatalf("error fetching configuration from the given file: %v", err)
}
fmt.Printf("Configuration: %q\n", configuration)
}
The code above outputs:
Configuration: {"setting1_value" "setting2_value"}