How to read a configuration file
Config.go
Package conf Import ("Bufio" "IO" "OS" "Strings") Func initconfig (path string) map[string]string { Initialize MYMAP: = Make (map[string]string)//Open file specify directory, return a file F and error message F, err: = OS. Open (path)//exception handling and ensure that function ends close file stream If Err! = Nil {panic (err)} defer f.close ()//create an output flow to the file Flush *reader r: = Bufio.
Newreader (f) for {//read, return []byte single slice to b b, _, Err: = R.readline () if err! = Nil { If err = = Io. EOF {break} panic (ERR)}//strips the space on both ends of the single-line attribute s: = strings. Trimspace (string (b))//fmt. PRINTLN (s)//To determine the equal sign = at the position of the line index: = strings. Index (s, "=") if Index < 0 {Continue}//Gets the key value to the left of the equal sign to determine if it is an empty key: = Strings . Trimspace (S[:index]) If Len (key) = = 0 {Continue}//Gets the value to the right of the equal sign to determine if it is empty Val UE: = Strings. Trimspace (s[index+1:]) ifLen (value) = = 0 {Continue}//In this case, the properties in the configuration file Key=value, successfully loaded into the in-memory C object Mymap[key] = Valu e} return MyMap}
Main.go
the package main import (
"conf" "
FMT"
)
func main () {
//import profile
Configmap: = Conf. Initconfig ("Src/db_configuration.txt")
//Gets the value FMT for the host property in the configuration
. Println (configmap["host"])
//View all the key values in the configuration file to the
FMT. Println (Configmap)
}
Db_configuration.txt
Host=localhost
port=5432
user=postgres
passwor=123
dbname=test
Results:
localhost
map[port:5432 user:postgres passwor:123 dbname:test Host:localhost]
It is worth noting that the path can write absolute path and relative path, that is, if the location of the db_configuration.txt is placed under the engineering and SRC peers, then "Src/db_configuration.txt", if placed in any place, you have to write the full path "g:\ Java_workspace\test_config\src\db_configuration.txt ", Slash to escape
In fact/and \ Equivalent, the left slash does not need to escape