本文参考自github上的一个项目,详细介绍了如何使用go语言解析和生成ini文件。以下是示例ini文件、结构体定义、解析代码、序列化代码以及调用示例的伪原创版本。
示例INI文件:
# 注释 ; 注释 ; 注释 <p>[redis] ip = 127.0.0.1 port = 8080</p><p>[mysql] host = 127.0.0.1 port = 3300 database = test user = root password = 123456 timeout = 30
结构体定义:
type RedisConfig struct {
Ip   string <pre class="brush:php;toolbar:false;">ini:"ip"
Port int    <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;">ini:"port"type MysqlConfig struct { Host string
ini:"host"
ini:"port"
ini:"database"
ini:"user"
ini:"password"
ini:"timeout"
type Config struct { RedisConfig RedisConfig
ini:"redis"
ini:"mysql"
解析INI文件的代码:
func unMarshalFile(fileName string, result interface{}) (err error) {
data, err := ioutil.ReadFile(fileName)
if err != nil {
return err
}
err = UnMarshal(data, result)
if err != nil {
return err
}
return
}</p><p>func UnMarshal(data []byte, result interface{}) (err error) {
typeInfo := reflect.TypeOf(result)
if typeInfo.Kind() != reflect.Ptr {
return nil
}
if typeInfo.Elem().Kind() != reflect.Struct {
return nil
}
lineArr := strings.Split(string(data), "\n")
var myFieldName string
for _, line := range lineArr {
line = strings.TrimSpace(line)
if len(line) == 0 || line[0] == ';' || line[0] == '#' {
continue
}
if line[0] == '[' {
myFieldName, err = myLabel(line, typeInfo.Elem())
if err != nil {
return
}
continue
}
err = myField(myFieldName, line, result)
if err != nil {
return
}
}
return
}</p><p>func myLabel(line string, typeInfo reflect.Type) (fieldName string, err error) {
labelName := line[1 : len(line)-1]
for i := 0; i < typeInfo.NumField(); i++ {
field := typeInfo.Field(i)
tag := field.Tag.Get("ini")
if tag == labelName {
fieldName = field.Name
return
}
}
err = fmt.Errorf("未找到标签:%s", labelName)
return
}</p><p>func myField(myFieldName string, line string, result interface{}) (err error) {
typeInfo := reflect.TypeOf(result).Elem()
valueInfo := reflect.ValueOf(result).Elem()
fieldIndex := -1
for i := 0; i < typeInfo.NumField(); i++ {
field := typeInfo.Field(i)
tag := field.Tag.Get("ini")
if tag == strings.Split(line, "=")[0] {
fieldIndex = i
break
}
}
if fieldIndex == -1 {
return fmt.Errorf("未找到字段:%s", strings.Split(line, "=")[0])
}
fieldValue := valueInfo.Field(fieldIndex)
switch fieldValue.Kind() {
case reflect.String:
fieldValue.SetString(strings.Split(line, "=")[1])
case reflect.Int:
intValue, <em> := strconv.Atoi(strings.Split(line, "=")[1])
fieldValue.SetInt(int64(intValue))
}
return
}结构体序列化的代码:
立即学习“go语言免费学习笔记(深入)”;
func MarshalFile(filename string, data interface{}) (err error) {
result, </em> := Marshal(data)
err = ioutil.WriteFile(filename, result, 0666)
return err
}</p><p>func Marshal(data interface{}) (result []byte, err error) {
typeInfo := reflect.TypeOf(data)
valueInfo := reflect.ValueOf(data)
if typeInfo.Kind() != reflect.Struct {
return
}
var conf []string
for i := 0; i < typeInfo.NumField(); i++ {
field := typeInfo.Field(i)
tag := field.Tag.Get("ini")
if tag != "" {
conf = append(conf, fmt.Sprintf("[%s]", tag))
fieldValue := valueInfo.Field(i)
switch fieldValue.Kind() {
case reflect.Struct:
subTypeInfo := fieldValue.Type()
subValueInfo := fieldValue
for j := 0; j < subTypeInfo.NumField(); j++ {
subField := subTypeInfo.Field(j)
subTag := subField.Tag.Get("ini")
if subTag != "" {
subFieldValue := subValueInfo.Field(j)
switch subFieldValue.Kind() {
case reflect.String:
conf = append(conf, fmt.Sprintf("%s=%s", subTag, subFieldValue.String()))
case reflect.Int:
conf = append(conf, fmt.Sprintf("%s=%d", subTag, subFieldValue.Int()))
}
}
}
}
}
}
result = []byte(strings.Join(conf, "\n"))
return
}调用示例:
package main</p><p>import "fmt"</p><p>func main() {
var conf Config
<em> = unMarshalFile("./config.ini", &conf)
fmt.Printf("成功解析文件 config:%#v\n port:%#v\n", conf, conf.RedisConfig.Port)
conf2 := Config{
RedisConfig{Ip: "127.0.0.1", Port: 6379},
MysqlConfig{Host: "127.0.0.1", User: "root", Password: "123456"},
}
</em> = MarshalFile("1.ini", conf2)
fmt.Printf("成功序列化文件\n")
}输出结果:

本文由仙士可原创,转载无需联系,但请注明来源于仙士可博客www.php20.cn。
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号