Answer the question
In order to leave comments, you need to log in
How to parse an option from a text config?
There is a text config in the following format:
// Global SQL settings
sql.db_hostname: 127.0.0.1
sql.db_port: 3306
sql.db_username: crux
sql.db_password: z8eGmcqYBAFpbvN4mypP
sql.db_port
into a variable? Answer the question
In order to leave comments, you need to log in
You can parse with your hands, everything is quite simple there
https://play.golang.org/p/Ug42O-eZnl
package main
import (
"fmt"
"strings"
)
func main() {
data := `// Global SQL settings
sql.db_hostname: 127.0.0.1
sql.db_port: 3306
sql.db_username: crux
sql.db_password: z8eGmcqYBAFpbvN4mypP`
config := ParseConfig(data)
fmt.Println(config["sql.db_port"])
}
func ParseConfig(data string) map[string]string {
parsed := make(map[string]string)
lines := strings.Split(data, "\n")
for _, line := range lines {
trimmedLine := strings.Trim(line, " \r\n")
if trimmedLine != "" && !strings.HasPrefix(trimmedLine, "//") {
pair := strings.SplitN(trimmedLine, ":", 2)
if len(pair) == 2 {
parsed[strings.Trim(pair[0], " ")] = strings.Trim(pair[1], " ")
}
}
}
return parsed
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question