Goconfig-Lesson 1:goconfig usage Analysis

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

Precautions

This blog belongs to Goconfig-class 1:goconfig Use resolution please pay attention to the use of matching.

This blog post is a companion blog for the Goconfig-go language INI parser, which is designed to explain the use and case of the library through text-to-code examples, making it easier for your classmates to use and learn more.

Library Introduction

Goconfig is a configuration file parser developed by the Go language for the common INI format under Windows. This parser is based on the operation of all INI files, and also expands on some requirements encountered in the actual development of the Go language. Compared to other INI file parsers, the greatest advantage of this parser is the excellent support for annotations, in addition to support for multiple configuration file overlay loading is also very special but useful features.

Download installation

There are two ways you can download the installation goconfig:

gopm get github.com/Unknwon/goconfig

Or

go get github.com/Unknwon/goconfig

API Documentation

Go Walker, please.

Basic Use Method

Sample code

In general, INI-formatted files are .ini suffixed, but you can use any suffix, which does not affect your use of the library for parsing. In this example, we use conf.ini the configuration file as our.

Load configuration file

To manipulate a configuration file, you need to load it into memory first, and we need to call LoadConfigFile the function to do the operation:

cfg, err := goconfig.LoadConfigFile("conf.ini")

The file name of the profile can be written relative to the path or absolute path, and the function returns the value of the ConfigFile and error type respectively. The variable is nil if there is an error in the load operation, cfg otherwise err nil. Once the loading is complete, we can manipulate the cfg data of the configuration file by manipulating the variables. Note that all data is stored in memory after loading, and any modifications to the file do not affect the object that has been acquired. In other words, the modification of the file at this time will not affect the cfg data in this object.

Basic read and write operations

The GetValue most basic read operation can be achieved by means of the method. In this case, the key key_default belongs to an unnamed partition (section), and the goconfig is directly attributed to DEFAULT the partition named by the parser. When we want to get the value of it, we can do the following:

value, err := cfg.GetValue(goconfig.DEFAULT_SECTION, "key_default")

The first return value is a string type, which is the value taken, the second return value is the error type and is not nil when an error occurs.

In addition to reading, you can set a value operation:

isInsert := cfg.SetValue(goconfig.DEFAULT_SECTION, "key_default", "这是新的值")

The method returns a value of type bool, indicating whether it is an insert operation. A value of TRUE indicates that the key did not exist before it was inserted successfully, otherwise the key already existed before it, and its value is now rewritten.

If you feel that it is cumbersome to call each time goconfig.DEFAULT_SECTION to represent DEFAULT a partition, you can also directly use a blank string to represent the DEFAULT partition:

value, err = cfg.GetValue("", "key_default")

The above code can also achieve the same effect.

In addition to using the equals sign as the delimiter between key values, the colon is also allowed:

key_super2 : 测试值

Comment Read and write operations

Although in most cases the program only reads data from the INI file, it is occasionally necessary to implement the write-to-file operation. At this point, all the rest of the parser will filter out the annotations, which is obviously undesirable when annotations are an important basis for the description of the configuration file. Therefore, it is not a feature of Goconfig to completely save the comments in the file and provide an API to manipulate the annotations in the program.

Goconfig allows your profile to start with a semicolon ; or a pound sign # on a separate line as a comment:

; 以分号开头的均为注释行# 以井号开头的也为注释行

But it cannot be in the middle of a line:

key_default = 默认节的一个键 # 注释必须单独占行,此处的注释无效

With the API provided by Goconfig, you can manipulate notes for a partition or key.

To get a comment for a partition:

comment := cfg.GetSectionComments("super")

To get a comment for a key:

comment = cfg.GetKeyComments("super", "key_super")

Both methods return the return value of type string.

To set a note for a key:

v := cfg.SetKeyComments("super", "key_super", "# 这是新的键注释")

To set a comment for a partition:

v = cfg.SetSectionComments("super", "# 这是新的分区注释")

The return values of the above two methods are of type bool. True indicates that the comment is inserted or deleted (when the passed argument is an empty string); False indicates that the comment already exists and is now overridden.

Type conversion Read

Goconfig provides methods that are named by type, such as Int , Int64 and, and Bool so on, that return values of non-string types and a return value of an error type to indicate whether an error occurred:

vInt, err := cfg.Int("must", "int")

The first return value is type int, and the second return value is the error type.

Must series method

The must series method is used to avoid code bloat caused by checking the error type, simplifying the data acquisition process. These methods all have Must characters that begin with, such as MustInt , MustInt64 and and MustBool so on. These methods are bound to return a value of the specified type, and if an error occurs, a value of 0 is returned, and no error occurs:

vBool := cfg.MustBool("must", "bool")

The method returns a value of type bool.

Delete the specified key value

When you want to discard a key, you can DeleteKey delete a key by means of a method:

ok := cfg.DeleteKey("must", "string")

The return value of this method is type bool, which indicates whether the delete operation was successful (it is not successful if the key does not exist).

Save configuration file

You can use a SaveConfigFile function to ConfigFile save the object as a string to the file system when the completion requires that the data be written back to the hard disk:

err = goconfig.SaveConfigFile(cfg, "conf_save.ini")

You need to specify the object and file name to save, which returns a value of type error.

Advanced Usage Tips

Sample code

The previous summary shows that if you use Goconfig to complete common INI file operations, this section will focus on some of the extended functionality that the Goconfig library brings to you.

Multi-File Overlay loading

A function LoadConfigFile can actually accept multiple arguments of type string to represent multiple configuration filenames to be loaded and to load them in a sequential manner:

cfg, err := goconfig.LoadConfigFile("conf.ini", "conf2.ini")

In this example, if the conf.ini conf2.ini same partition and key name are present at the same time as in, only the conf2.ini values in the file are obtained.

If you find that you need to add a configuration file while the program is running, you can use the method to AppendFiles implement the append operation:

err = cfg.AppendFiles("conf3.ini")

Configuration file Overloading

If the external file has been modified, it can be quickly overloaded by calling the method:

err = cfg.Reload()

The method returns a value of type error indicating whether the operation was successful.

Set default values for must series methods

With the function of the Go language variable, when the must series method has three parameters, the third parameter is the default value when the failure is obtained:

vBool := cfg.MustBool("must", "bool404", true)

In this case, the key name bool404 does not exist at all, and true is used as the return value.

Recursive reading of key values

In the file conf3.ini , the default partition has two keys as follows:

google=www.google.comsearch=http://%(google)s

When you use %( )s a key name as a value, Goconfig will look for the value of the corresponding key to replace it, and if the value of the replaced key has such a nesting, the substitution will be executed recursively. This operation allows nesting of up to 200 layers. At this point, the search actual value of the key is http://www.google.com . Note that the included keys can be either in DEFAULT the partition or the same partition, in the order in which they appear.

Descendant Partition Overlay Read

In the file conf3.ini , the following configuration is available:

[parent]name=johnrelation=fathersex=maleage=32[parent.child]age=3

When we get the parent.child key in the partition age we get it, 3 but when we want to get sex it, it should normally be a fail, but Goconfig will find the parent.child parent partition parent because parent.child the half-width symbol is used to achieve grading. At this time, the gain sex will get male .

Self-increment key name acquisition

In the file conf3.ini , the following configuration is available:

[auto increment]-=hello-=go-=config

Because it is used - as the key name, Goconfig will translate it into a self-increment number starting at 1 when parsing. In this example, the above key is saved in the object as:

#1: hello#2: go#3: config

Note that the count is only valid within the same partition, and the new partition will be counted again starting at 1.

Get the entire partition

If you want to manipulate a partition directly, you can use the method GetSection to return a value of type map[string]string that contains all the key-value pairs for the corresponding partition:

sec, err := cfg.GetSection("auto increment")

Summarize

The API of the Goconfig package is very comprehensive, the usage is very simple, but the core code is not many, the students are interested to read its source code.

Use case

    • gopm
    • beego-i18n
    • Beeweb
    • Wetalk
    • Gowalker
Related Article

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.