golang 简易的键值配置包

type Setting struct {
	path string
	prefix string
	set map[string]interface{}
}

func NewSetting(file string) *Setting{
	s := Setting{}
	s.path = file
	s.set = make(map[string]interface{})
	return &s
}

func (s *Setting)load(){
	s.clear()

	f,err := os.Open(s.path)
	if err != nil{
		fmt.Println(err)
		return
	}

	//扫描行并分割处理
	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		text := scanner.Text()
		if len(text) < 3 || !strings.Contains(text,"="){
			continue
		}

		stringList := strings.Split(text,"=",)
		//fmt.Println(reflect.TypeOf(value))
		s.setValue(strings.TrimSpace(stringList[0]),strings.TrimSpace(stringList[1]))
		//mt.Println(scanner.Text())
	}

	err = scanner.Err()
	if err != nil {
		log.Fatal(err)
	}
}

func (s *Setting)loadByFile(file string){
	s.path = file
	s.load()
}

func (s *Setting)save(){
	f,err := os.Create(s.path)
	if err != nil {
		fmt.Println(err)
		return
	}

	defer f.Close()
	for k,v:= range s.set {
		switch v.(type) {
		case int:
			f.WriteString(fmt.Sprintf("%s=%d\r\n",k,v))
		case float64:
			f.WriteString(fmt.Sprintf("%s=%f\r\n",k,v))
		case string:
			//f.WriteString(fmt.Sprintf("%s=\"%s\"\r\n",k,v))
			f.WriteString(fmt.Sprintf("%s=%s\r\n",k,v))
		case bool:
			f.WriteString(fmt.Sprintf("%s=%t\r\n",k,v))
		default:
			f.WriteString(fmt.Sprintf("%s=%v\r\n",k,v))
		}
	}
}

func (s *Setting)saveByFile(file string){
	s.path = file
	s.save()
}

func (s *Setting)setValue(key string,value interface{}){
	s.set[key] = value
}

func (s *Setting)value(key string)interface{}{
	return s.set[key]
}

func (s *Setting)valueByDefault(key string,value interface{})interface{}{
	if s.contains(key) {
		return s.value(key)
	}
	return value
}

func (s *Setting)clear(){
	for k := range s.set{
		delete(s.set,k)
	}
}

func (s *Setting)beginGroup(prefix string){
	s.prefix = prefix
}

func (s *Setting)endGroup(){
	s.prefix = ""
}

func (s *Setting)contains(key string)bool{
	if _,find := s.set[key];find{
		return true
	}else{
		return false
	}
}

func (s *Setting)fileName()string{
	return s.path
}

func (s *Setting)remove(key string){
	delete(s.set,key)
}

func (s *Setting)sync(){

}

func (s *Setting)allKeys()[]string{
	keys := make([]string,len(s.set))
	for k:= range s.set{
		keys = append(keys,k)
	}
	return keys
}
posted @ 2020-03-04 14:37  學海無涯  阅读(174)  评论(0编辑  收藏  举报