Files
go-mqtt/config/config.go
2024-08-21 15:32:05 +08:00

48 lines
1.2 KiB
Go

package config
import (
"encoding/json"
"gopkg.in/yaml.v3"
"testmqtt/listeners"
"testmqtt/mqtt"
)
// config 定义配置结构
// config defines the structure of configuration data to be parsed from a config source.
type config struct {
Options mqtt.Options // Mqtt协议配置
Listeners []listeners.Config `yaml:"listeners" json:"listeners"` // 监听端口配置
HookConfigs HookConfigs `yaml:"hooks" json:"hooks"` // 钩子配置
LoggingConfig LoggingConfig `yaml:"logging" json:"logging"` // 日志记录配置
}
// FromBytes unmarshals a byte slice of JSON or YAML config data into a valid server options value.
// Any hooks configurations are converted into Hooks using the toHooks methods in this package.
func FromBytes(b []byte) (*mqtt.Options, error) {
c := new(config)
o := mqtt.Options{}
if len(b) == 0 {
return nil, nil
}
if b[0] == '{' {
err := json.Unmarshal(b, c)
if err != nil {
return nil, err
}
} else {
err := yaml.Unmarshal(b, c)
if err != nil {
return nil, err
}
}
o = c.Options
o.Hooks = c.HookConfigs.ToHooks()
o.Listeners = c.Listeners
o.Logger = c.LoggingConfig.ToLogger()
return &o, nil
}