Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing values from property file in golang

Tags:

go

For Java there is the Properties class that offers functionality to parse / interact with property file.

Is there something similar in golang standard library ?

If not, what other alternatives do I have ?

like image 882
shagul Avatar asked Oct 13 '16 13:10

shagul


2 Answers

Adding on top of @Madhu's answer, you can create a very simple package to read a properties file using Scanner, and read line by line of your file skipping invalid lines (those not having the '=' char):

Example:

package fileutil

import (
    "bufio"
    "os"
    "strings"
    "log"
)

type AppConfigProperties map[string]string

func ReadPropertiesFile(filename string) (AppConfigProperties, error) {
    config := AppConfigProperties{}

    if len(filename) == 0 {
        return config, nil
    }
    file, err := os.Open(filename)
    if err != nil {
        log.Fatal(err)
        return nil, err
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line := scanner.Text()
        if equal := strings.Index(line, "="); equal >= 0 {
            if key := strings.TrimSpace(line[:equal]); len(key) > 0 {
                value := ""
                if len(line) > equal {
                    value = strings.TrimSpace(line[equal+1:])
                }
                config[key] = value
            }
        }
    }

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

    return config, nil
}

Sample test sample_test.properties :

host=localhost
proxyHost=test
protocol=https://
chunk=

Properties test:

package fileutil

import (
    "testing"
)

func TestReadPropertiesFile(t *testing.T) {
    props, err := ReadPropertiesFile("sample_test.properties")
    if err != nil {
        t.Error("Error while reading properties file")
    }

    if props["host"] != "localhost" || props["proxyHost"] != "test" || props["protocol"] != "https://" || props["chunk"] != "" {
        t.Error("Error properties not loaded correctly")
    }

}
like image 105
guilhebl Avatar answered Oct 14 '22 17:10

guilhebl


You can use this following code Instead of using 3rd Party libs

package main

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

type Config map[string]string

func ReadConfig(filename string) (Config, error) {
    // init with some bogus data
    config := Config{
        "port":     "8888",
        "password": "abc123",
        "ip":       "127.0.0.1",
    }
    if len(filename) == 0 {
        return config, nil
    }
    file, err := os.Open(filename)
    if err != nil {
        return nil, err
    }
    defer file.Close()

    reader := bufio.NewReader(file)

    for {
        line, err := reader.ReadString('\n')

        // check if the line has = sign
        // and process the line. Ignore the rest.
        if equal := strings.Index(line, "="); equal >= 0 {
            if key := strings.TrimSpace(line[:equal]); len(key) > 0 {
                value := ""
                if len(line) > equal {
                    value = strings.TrimSpace(line[equal+1:])
                }
                // assign the config map
                config[key] = value
            }
        }
        if err == io.EOF {
            break
        }
        if err != nil {
            return nil, err
        }
    }
    return config, nil
}

func main() {
    // for this tutorial, we will hard code it to config.txt
    config, err := ReadConfig(`C:\Users\mseelam.ORADEV\GoglandProjects\MyFirstProj\data\config`)

    if err != nil {
        fmt.Println(err)
    }

    //fmt.Println("Config data dump :", config)

    // assign values from config file to variables
    ip := config["ip"]
    pass := config["pass"]
    port := config["port"]

    fmt.Println("IP :", ip)
    fmt.Println("Port :", port)
    fmt.Println("Password :", pass)
}
like image 7
Madhu Kiran Seelam Avatar answered Oct 14 '22 18:10

Madhu Kiran Seelam