golang支持HOCON格式配置解析与管理的插件库hocon的使用

Golang支持HOCON格式配置解析与管理的插件库hocon的使用

HOCON (Human-Optimized Config Object Notation) 是一种人性化的JSON超集配置格式。

HOCON特性

  • 支持#//注释
  • 允许省略根对象的{}
  • 允许使用=作为:的同义词
  • 允许省略对象前的=:,如foo { a : 42 }
  • 允许省略逗号(只要有换行)
  • 允许对象和数组最后一个元素后加逗号
  • 允许键和值使用未加引号的字符串
  • 未加引号的键可以使用点表示法表示嵌套对象
  • 允许重复键(后面的值会覆盖前面的)
  • 支持include功能合并其他配置文件
  • 支持变量替换${a.b}
  • 支持环境变量替换
  • 支持数组追加语法+=
  • 支持类似Python或Scala的三引号多行字符串

安装

go get -u github.com/gurkankaymak/hocon

使用示例

下面是一个完整的HOCON配置解析示例:

package main

import (
    "fmt"
    "log"
    "github.com/gurkankaymak/hocon"
)

func main() {
    hoconString := `
    booleans {
      trueVal: true
      trueValAgain: ${booleans.trueVal}
      trueWithYes: yes
      falseWithNo: no
    }
    // this is a comment
    #  this is also a comment
    numbers {
      intVal: 3
      floatVal: 1.0
    }
    strings {
      a: "a"
      b: "b"
      c: "c"
    }
    arrays {
      empty: []
      ofInt: [1, 2, 3]
      ofString: [${strings.a}, ${strings.b}, ${strings.c}]
      ofDuration: [1 second, 2h, 3 days]
    }
    durations {
      second: 1s
      halfSecond: 0.5 second
      minutes: 5 minutes
      hours: 2hours
      day: 1d
    }
    objects {
      valueObject {
        mandatoryValue: "mandatoryValue"
        arrayValue: ${arrays.ofInt}
        nullValue: null
      }
    }`

    // 解析HOCON字符串
    conf, err := hocon.ParseString(hoconString)
    if err != nil {
        log.Fatal("error while parsing configuration: ", err)
    }

    // 获取各种类型的配置值
    objectValue := conf.GetObject("objects.valueObject")
    arrayValue := conf.GetArray("arrays.ofInt")
    stringValue := conf.GetString("strings.a")
    intValue := conf.GetInt("numbers.intVal")
    floatValue := conf.GetFloat64("numbers.floatVal")
    durationValue := conf.GetDuration("durations.second")

    // 打印获取的值
    fmt.Println("objectValue:", objectValue) // {mandatoryValue:mandatoryValue, arrayValue:[1,2,3], nullValue:null}
    fmt.Println("arrayValue:", arrayValue)  // [1,2,3]
    fmt.Println("stringValue:", stringValue) // a
    fmt.Println("intValue:", intValue)     // 3
    fmt.Println("floatValue:", floatValue) // 1.0
    fmt.Println("durationValue:", durationValue) // 1s
    fmt.Println("all configuration:", conf)
}

主要功能

  1. 解析HOCON配置:使用hocon.ParseString()方法解析HOCON格式的字符串
  2. 获取配置值
    • GetObject() - 获取对象
    • GetArray() - 获取数组
    • GetString() - 获取字符串
    • GetInt() - 获取整数值
    • GetFloat64() - 获取浮点数值
    • GetDuration() - 获取时间间隔值

这个库提供了简单易用的API来解析和管理HOCON格式的配置文件,支持HOCON的所有特性,是Golang项目中处理复杂配置的理想选择。


更多关于golang支持HOCON格式配置解析与管理的插件库hocon的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang支持HOCON格式配置解析与管理的插件库hocon的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang HOCON配置解析与管理

HOCON (Human-Optimized Config Object Notation) 是一种基于JSON的配置格式,由Lightbend公司(原Typesafe)开发,主要用于Akka和Play框架。在Golang中,我们可以使用go-hocon库来解析和管理HOCON格式的配置文件。

安装go-hocon

首先安装go-hocon库:

go get github.com/go-akka/configuration

基本用法

1. 解析HOCON文件

假设我们有一个application.conf文件:

app {
  name = "MyApp"
  version = "1.0.0"
  database {
    url = "jdbc:mysql://localhost:3306/mydb"
    username = "admin"
    password = "secret"
    pool-size = 10
  }
  features = ["logging", "metrics", "cache"]
}

解析代码:

package main

import (
	"fmt"
	"github.com/go-akka/configuration"
	"log"
)

func main() {
	// 加载HOCON配置文件
	conf, err := configuration.LoadConfig("application.conf")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// 获取配置值
	appName := conf.GetString("app.name")
	version := conf.GetString("app.version")
	dbUrl := conf.GetString("app.database.url")
	poolSize := conf.GetInt32("app.database.pool-size")
	features := conf.GetStringList("app.features")

	fmt.Printf("App Name: %s\n", appName)
	fmt.Printf("Version: %s\n", version)
	fmt.Printf("DB URL: %s\n", dbUrl)
	fmt.Printf("Pool Size: %d\n", poolSize)
	fmt.Printf("Features: %v\n", features)
}

2. 支持的类型和获取方法

go-hocon支持多种数据类型:

// 字符串
str := conf.GetString("path.to.string", "default")

// 布尔值
boolVal := conf.GetBoolean("path.to.boolean", false)

// 整数
intVal := conf.GetInt32("path.to.int", 0)
int64Val := conf.GetInt64("path.to.int64", 0)

// 浮点数
floatVal := conf.GetFloat64("path.to.float", 0.0)

// 字符串列表
strList := conf.GetStringList("path.to.list")

// 配置对象
subConf := conf.GetConfig("path.to.subconfig")

// 时间持续时间
duration := conf.GetTimeDuration("path.to.duration", time.Second)

3. 合并多个配置文件

HOCON支持配置继承和合并:

// 加载基础配置
baseConf, _ := configuration.LoadConfig("base.conf")

// 加载环境特定配置
envConf, _ := configuration.LoadConfig("prod.conf")

// 合并配置
mergedConf := baseConf.WithFallback(envConf)

4. 环境变量替换

HOCON支持环境变量替换:

app {
  home = ${HOME}
  temp = ${TEMP:/tmp}  # 默认值
}

5. 引用其他值

HOCON支持引用其他配置值:

app {
  name = "MyApp"
  full-name = ${app.name} Professional Edition
}

高级特性

1. 配置监听与热更新

// 创建一个可监听的配置源
configSource := configuration.NewDefaultConfigSource("application.conf")

// 添加监听器
configSource.AddListener(func(event configuration.ConfigChangeEvent) {
    fmt.Printf("Config changed: %v\n", event)
})

// 定期检查配置更新
go func() {
    for {
        time.Sleep(30 * time.Second)
        configSource.CheckForUpdates()
    }
}()

2. 生成HOCON配置

conf := configuration.NewConfig()
conf.Set("app.name", "MyApp")
conf.Set("app.version", "1.0.0")
conf.Set("app.database.url", "jdbc:mysql://localhost:3306/mydb")

// 转换为HOCON字符串
hoconStr := conf.String()
fmt.Println(hoconStr)

3. 验证配置

// 定义配置结构体
type AppConfig struct {
    Name    string
    Version string
    DB      struct {
        URL      string
        Username string
        Password string
    }
}

// 解析到结构体
var appConfig AppConfig
if err := conf.Unmarshal(&appConfig); err != nil {
    log.Fatalf("Failed to unmarshal config: %v", err)
}

注意事项

  1. HOCON是JSON的超集,所有JSON文件都是有效的HOCON文件
  2. 支持注释(//和#)
  3. 支持多行字符串(使用三引号""")
  4. 支持包含其他文件(include "other.conf")
  5. 键可以不加引号(如果它们是简单的标识符)

go-hocon库提供了丰富的功能来处理HOCON配置,使得在Golang项目中使用HOCON变得非常简单和方便。

回到顶部