This tutorial explains about below things

  • How to Parse properties file key and values in Golang
  • How to write properties files in Golang.

Properties files contain multiple lines where each line contains a key and value separated by equal(=).

There are no packages required separately for reading and writing properties files.

Golang native libraries os and bufio are used to process properties file.

Sample Properties file

author= Franc
driver= com.mysql.jdbc.Driver
port= 3306
dbname= students
username= root
password= root

Golang Read properties file values

Following are steps to write a code for parsing keys and values of a properties file.

  • Import required below packages
    • bufio for buffer IO access
    • fmt for console print
    • os for opening and closing files
    • strings for converting properties key and values into a map of strings
  • Create a function readPropertiesFile that takes the path of a file and returns a Map of strings and an error
    • This function opens the file and reads content into a variable file, err is thrown if any IO operations.
    • Initialize the map using make(map[string]string) for storing properties data in a map
    • using bufio.NewScanner() to read the file content line by line until the end of a file.
    • read each line of file content into a variable
    • Pass the variable to strings.SplitN() to split using separator (=), the result is keya and values.
    • remove the spaces from a value using the strings.TrimSpace function
    • Save the key and values to a Map.
    • Finally, the Map is returned from the function
  • Call the function with a file path, and return a Map of key and value pairs read from properties.
  • Finally, Print the map using a for loop with values. Here is an example
package main

import (
  "bufio"
  "fmt"
  "os"
  "strings"
)

func readPropertiesFile(filePath string) (map[string]string, error) {
  file, err := os.Open(filePath)
  if err != nil {
    return nil, err
  }
  defer file.Close()

  properties := make(map[string]string)

  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    line := scanner.Text()
    parts := strings.SplitN(line, "=", 2)
    if len(parts) == 2 {
      key := strings.TrimSpace(parts[0])
      value := strings.TrimSpace(parts[1])
      properties[key] = value
    }
  }

  if err := scanner.Err(); err != nil {
    return nil, err
  }

  return properties, nil
}

func main() {
  filePath := "config.properties"
  properties, err := readPropertiesFile(filePath)
  if err != nil {
    fmt.Println("Error reading properties file:", err)
    return
  }

  // Print the read properties
  fmt.Println("Properties:")
  for key, value := range properties {
    fmt.Printf("%s = %s\n", key, value)
  }
}

How to write a map of keys and values into a properties file

This example covers the Map in Golang is written to the Properties file.

  • Import required fmt and os packages into a code
  • Create a Map of the Key and values of a string.
  • Pass the Map variable to a function with a given file path
  • Inside a function Create a file using the os.Create() function, It creates a file for successful execution, else error is thrown if any IO Error.
  • Iterate map using range loop
  • Save each item to a file using the fmt.Fprintf() function.

Complete example for writing to the properties file

package main

import (
  "fmt"
  "os"
)

func writePropertiesFile(filePath string, properties map[string]string) error {
  file, err := os.Create(filePath)
  if err != nil {
    return err
  }
  defer file.Close()

  for key, value := range properties {
    _, err := fmt.Fprintf(file, "%s = %s\n", key, value)
    if err != nil {
      return err
    }
  }

  return nil
}

func main() {
  filePath := "config.properties"
  propertiesData := map[string]string{
    "url": "localhost",
    "username": "root",
    "password": "root",
  }

  err := writePropertiesFile(filePath, propertiesData)
  if err != nil {
    fmt.Println("Error writing properties file:", err)
    return
  }

  fmt.Println("Golang Map is written to Proer")
}