github.com/qiniu/x@v1.11.9/config/load_conf.go (about)

     1  package config
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"flag"
     7  	"io/ioutil"
     8  
     9  	"github.com/qiniu/x/log"
    10  )
    11  
    12  var (
    13  	confName *string
    14  )
    15  
    16  func Init(cflag, app, default_conf string) {
    17  
    18  	confDir, _ := GetDir(app)
    19  	confName = flag.String(cflag, confDir+"/"+default_conf, "the config file")
    20  }
    21  
    22  func GetPath() string {
    23  
    24  	if confName != nil {
    25  		return *confName
    26  	}
    27  	return ""
    28  }
    29  
    30  func Load(conf interface{}) (err error) {
    31  
    32  	if !flag.Parsed() {
    33  		flag.Parse()
    34  	}
    35  
    36  	log.Info("Use the config file of ", *confName)
    37  	return LoadEx(conf, *confName)
    38  }
    39  
    40  func LoadEx(conf interface{}, confName string) (err error) {
    41  
    42  	data, err := ioutil.ReadFile(confName)
    43  	if err != nil {
    44  		log.Error("Load conf failed:", err)
    45  		return
    46  	}
    47  	data = trimComments(data)
    48  
    49  	err = json.Unmarshal(data, conf)
    50  	if err != nil {
    51  		log.Error("Parse conf failed:", err)
    52  	}
    53  	return
    54  }
    55  
    56  func LoadFile(conf interface{}, confName string) (err error) {
    57  
    58  	data, err := ioutil.ReadFile(confName)
    59  	if err != nil {
    60  		return
    61  	}
    62  	data = trimComments(data)
    63  
    64  	return json.Unmarshal(data, conf)
    65  }
    66  
    67  func LoadBytes(conf interface{}, data []byte) (err error) {
    68  
    69  	return json.Unmarshal(trimComments(data), conf)
    70  }
    71  
    72  func LoadString(conf interface{}, data string) (err error) {
    73  
    74  	return json.Unmarshal(trimComments([]byte(data)), conf)
    75  }
    76  
    77  func trimComments(data []byte) (data1 []byte) {
    78  
    79  	var line []byte
    80  
    81  	data1 = data[:0]
    82  	for {
    83  		pos := bytes.IndexByte(data, '\n')
    84  		if pos < 0 {
    85  			line = data
    86  		} else {
    87  			line = data[:pos+1]
    88  		}
    89  		data1 = append(data1, trimCommentsLine(line)...)
    90  		if pos < 0 {
    91  			return
    92  		}
    93  		data = data[pos+1:]
    94  	}
    95  }
    96  
    97  func trimCommentsLine(line []byte) []byte {
    98  
    99  	n := len(line)
   100  	quoteCount := 0
   101  	for i := 0; i < n; i++ {
   102  		c := line[i]
   103  		switch c {
   104  		case '\\':
   105  			i++
   106  		case '"':
   107  			quoteCount++
   108  		case '#':
   109  			if (quoteCount & 1) == 0 {
   110  				return line[:i]
   111  			}
   112  		}
   113  	}
   114  	return line
   115  }