[Golang] Self-implementation INI file read

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

Recently infatuated with the go language, but I am a novice programmer, this read Reference Beego config, only semi-finished, but can run normally.

    1. Design of the interface
Type Parser Interface {Parse () Error}type Config Interface {GetString (string) Stringparser}

Currently only minimal operations, parsing and fetching are supported. To have config instantiate an object before reading it:

var config configfunc registerconfig (mode,path string) {switch mode{case "ini": Config=ini. Newiniconfig (path) case "JSON": Case "xml":d efault:panic ("Dosn ' t supported configure type.")}}

Thus, as long as Iniconfig implements the Config interface, the instantiated object can be assigned to config, which is global and externally called CONFIG. Regi ... Then, call the encapsulated operation to get the instance and implement the function.

Global implementation: Util.go

Package Configimport "Mytools/config/ini" type Parser interface {Parse () Error}type config interface {GetString (string) Stringparser}var config Configfunc registerconfig (mode,path string) {switch mode{case "ini": Config=ini. Newiniconfig (path) case "JSON": Case "xml":d efault:panic ("Dosn ' t supported configure type.")}} Func getconfig () *config{return &config}

Iniconfig implementation

Package Iniimport ("OS" "Sync" "Bufio" "io" "bytes" "Strings" "Log") var (default_section stringcomment []byteseparator [] Byte//section_start string//section_end String)//const (//left = iota//right//) func init () {default_section= "DEFAULT" comment=[]byte{' # '}separator=[]byte{' = '}}//type entryconfig struct {//isalign bool//aligned//aligntype INT//alignment type//}type inientry struct {Value interface {}}type iniconfig struct {filename stringsection Map[string]*inisectionsync.rwmutex} Func newiniconfig (Path string) *iniconfig{config:=&iniconfig{path,make (map[string]*inisection), sync. Rwmutex{}}config.section[default_section]=newinisection () return Config}func (c *iniconfig) Parse () error{file,err:= Os. Open (c.filename) if Err!=nil {return Err}c.lock () defer c.unlock () defer file. Close () Buf:=bufio. Newreader (file) Section:=default_sectionvar Bufread intfor{//reads a row of cache line,_,err:=buf. ReadLine () Bufread = Bufread + len (line) if Err==io. eof{//reads the end of the file and exits the loop break}if bytes. Equal (Line,[]byte ("")) {//Blank lines skip loops directly continue}//delete white space characters at both ends of the row line=bytes. Trimspace (line) if bytes. Hasprefix (line,comment) {//comment lines are temporarily not processed continue}if bytes. Hasprefix (Line,[]byte ("[")) &&bytes. Hassuffix (Line,[]byte (")")) {//section processing//Now line determined as "[sectioname]"//Don't know if there is a legality check section=string (line)-1 ]) section=strings. ToLower (section) if _,ok:=c.section[section];! Ok{c.section[section]=newinisection ()}}else{//key=value handles pair:= bytes. SPLITN (line,separator,2) key:= pair[0]val:=pair[1]if _,ok:=c.section[section];! Ok{c.section[section]=newinisection ()}log. Println (Key,val) c.section[section].addentry (String (key), String (val))}}return Nil}func (c *iniconfig) removesection (Key string) Error{return Nil}func (c *iniconfig) GetString (k string) string{s:=strings. Split (k, ":") var sec stringvar key Stringif Len (s) ==1{sec=default_sectionkey=s[0]log. Println (Sec,key)}else{sec=s[0]key=s[1]log. Println (Sec,key)}if v,ok:=c.section[sec].getentry (key). (string); Ok{return V}return ""}
First look at the structure, INI file the most basic composition by the comments, modules, three parts of the item, where the comment line may be the beginning of a specific character, such as "#", ";" And so on, now the default is "#", if you want to support custom characters, add interface and check operation can be implemented. We have defined the default action when the module is loaded. See init function.
Looking back at Section,iniconfig is a tree structure with a depth of 2, each tree with a node is sectionname, the child node is a configuration item key=value, the default has a defaultsection.
In terms of parsing, read by line, and then according to the INI file characteristics, processing comment lines, comment segments (not implemented), sections, and items, and then convert them into data structures saved in Iniconfig, as long as the call GetString can get configuration items, the syntax is "section: Key ".
Well, let's get here first.

Rookie light spray .....


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.