github.com/searKing/golang/go@v1.2.117/encoding/ini/read.go (about)

     1  // Copyright 2022 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package ini
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"fmt"
    11  	"io"
    12  	"os"
    13  	"strings"
    14  )
    15  
    16  func ReadConfigFile(name string) (*Config, error) {
    17  	data, err := os.ReadFile(name)
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  
    22  	return ReadConfig(data)
    23  
    24  }
    25  
    26  func ReadConfig(data []byte) (*Config, error) {
    27  	cfg := NewConfig()
    28  
    29  	if err := cfg.Read(bytes.NewBuffer(data)); err != nil {
    30  		return nil, err
    31  	}
    32  
    33  	return cfg, nil
    34  }
    35  
    36  func (c *Config) Read(r io.Reader) error {
    37  	rb := bufio.NewReaderSize(r, 4096)
    38  
    39  	for {
    40  		l, err := rb.ReadString('\n')
    41  		if err != nil && err != io.EOF {
    42  			return err
    43  		} else if err == io.EOF {
    44  			break
    45  		}
    46  
    47  		l = strings.TrimSpace(l)
    48  		if len(l) == 0 {
    49  			continue
    50  		}
    51  
    52  		//comment
    53  		if l[0] == '#' {
    54  			continue
    55  		}
    56  
    57  		ps := strings.Split(l, "=")
    58  		if len(ps) > 2 {
    59  			return fmt.Errorf("invalid line format %s", l)
    60  		} else if len(ps) == 1 {
    61  			c.SetString(ps[0], "")
    62  		} else {
    63  			c.SetString(strings.TrimSpace(ps[0]), strings.TrimSpace(ps[1]))
    64  		}
    65  	}
    66  	return nil
    67  }