Golang JSON configuration file processing

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The configuration is divided into two parts, the system startup parameters using the file, business parameters using the NoSQL class of memory database, here only to discuss the file, the database to stay in the future;
Use JSON instead of INI format configuration file;
The parsing of the configuration file does not need to take into account the content, as long as the format is correct, need to configure the module to get the required fields.
First you need to get the configuration file path, consider two ways: 1. Command-line arguments provided; 2. The default file is used when command line arguments are not provided.

var profile stringflag.StringVar(&profile, "profile", os.Getenv("GOETC")+"/profile.json", "Full path of the profile.")flag.Parse()

Of course you need to include the flag package and the OS package first.
OS Package is platform independent operating system interface, for example, the above getenv,linux corresponds to getenv, you can see the parameters are consistent. $GOETC defined in. bash_profile. When it comes to this, you can actually put a lot of startup parameters into the. Bash_profile, but it's just a choice, not a discussion.
Flag packets are specifically used to parse command-line arguments. As far as the Stringvar function is concerned, the first parameter holds the command line arguments that are read in, the second parameter is the name of the command line argument, the third parameter is the default value, and the fourth parameter is the so-called usage.
Taking the above procedure as an example, assuming that the command line argument is-profile=./profile.json, then the variable profile is "./profile.json" After the function is returned. If we start the program without the profile of the command line, The value of the variable profile will be $goetc/profile.json.
We can use-H to get the so-called usage, which will be printed in this program

Usage of mytchSever:-profile stringFull path of the profile. (default "/home/whg/work/etc/profile.json")

Set the configuration file content is a JSON-formatted text document, with # or, at the beginning of the behavior comment:

{#no comments     "tcpPort":12345,    "httpPort":8080,    "httpsPort":436,    "others":{        "item1":"string",        "item2":false    }}

After you get the full path to the configuration file, you can open and read the content.

    profilefd, err := os. Open (Profile)     if err != nil {         Panic (Err)     }    defer profilefd.close ()      buffer := bufio. Newreader (PROFILEFD)     var profileLines string    for  {        line, err := buffer. ReadString (' \ n ')         if err == io. eof {            break         } else if line[0] ==  ' # '  | |  line[0] ==  '; '  {            continue         } else If Err! = Nil {            Panic (err)        }         profilelines+= line    }

Need to include IO and BUFIO packages. Of course, the operation of the file is not only bufio this way, since it is text, read by line is to be simpler, moreover, the program efficiency is not the way to read the configuration file.
Speaking of which, we need to explain the next strings. Trim series function, just beginning to think is directly modify the original string, look at the document only to find that the result is returned by the return value.
The next step is to parse the JSON string that has been read:

var ProfileItems map[string]interface{} //全局变量

    jsonLines := []byte(profileLines)    if err := json.Unmarshal(jsonLines, &ProfileItems); err != nil {        panic(err)    }    httpPort := ProfileItems["httpPort"].(float64)    httpsPort := ProfileItems["httpsPort"].(float64)    tcpPort := ProfileItems["tcpPort"].(float64)    others := ProfileItems["others"].(map[string]interface{})    item1 := others["item1"].(string)    item2 := others["item2"].(bool)

One thing to note is that Jsonlines is a slice initialized with Profilelines, and the other one is the processing of the others domain, and of course it is very straightforward.
This is all the code so far:

Package mainimport  (     "Bufio"      "Encoding/json"       "Flag"      "FMT"      "io"      "OS"      //  "Strings"     //"Unicode/utf8") var profileitems map[string] Interface{} //obviously,this var would be Used in many Filesfunc main ()  {    var Profile string    flag. Stringvar (&profile,  "Profile",  os. Getenv ("goetc") + "/profile.json",  "full path of the profile.")     flag. Parse ()         profilefd, err := os. Open (Profile)     if err != nil {         Panic (Err)     }    defer profilefd.close ()      buffer := bufio. Newreader (PROFILEFD)   &nbsP; var profilelines string    for {         line, err := buffer. ReadString (' \ n ')         if err == io. eof {            break         } else if line[0] ==  ' # '  | |  line[0] ==  '; '  {            continue         } else if err != nil {             panic (Err)         }         profileLines += line  }     jsonlines := []byte (Profilelines)     if err := json. UnmArshal (Jsonlines, &profileitems); err != nil {         panic (Err)     }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.