Golang : Read data from config file and assign to variables
Usually a large program will need multiple parameters to function properly and the parameters will determine the behavior of the program. A good programmer will make his or her program to accept parameters from command line, environment or read from a file.
In this tutorial, we will learn how to read data from a plain text config file - simulating a program reading parameters from a file.
Here you go!
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(`config.txt`)
if err != nil {
fmt.Println(err)
}
//fmt.Println("Config data dump :", config)
// assign values from config file to variables
ip := config["ip"]
pass := config["password"]
port := config["port"]
fmt.Println("IP :", ip)
fmt.Println("Port :", port)
fmt.Println("Password :", pass)
}
Reading a sample config.txt file :
[profile manager]
key=value
password = sjssh31mmv
; a comment
port = 8080
ip = 123.456.789.321
# another comment
url=example.com
file=
# last comment
Sample output :
IP : 123.456.789.321
Port : 8080
Password : sjssh31mmv
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+12.3k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+29.5k Golang : Get time.Duration in year, month, week or day
+29k Golang : JQuery AJAX post data to server and send data back to client example
+5.6k Cash Flow : 50 days to pay your credit card debt
+7.5k Golang : Lock executable to a specific machine with unique hash of the machine
+12k Golang : calculate elapsed run time
+13.7k Golang : concatenate(combine) strings
+4.8k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+22.5k Golang : simulate tail -f or read last line from log file example
+8.7k Golang : Get SPF and DMARC from email headers to fight spam
+35.8k Golang : How to split or chunking a file to smaller pieces?