L
L
landergate2016-05-11 18:54:05
go
landergate, 2016-05-11 18:54:05

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

How can I take the value of an option sql.db_portinto a variable?
A live code example is welcome.
What I tried:
https://github.com/go-ini/ini
https://github.com/Unknwon/goconfig
but in my config there is no [section] above the options, and ways to parse without it in the documentation or code of these projects I couldn't find.
https://github.com/spf13/viper - can't INI/colon You can't
change the config format, it's a third party project.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2016-05-11
@landergate

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 question

Ask a Question

731 491 924 answers to any question