[config] 初步实现yaml配置读取

This commit is contained in:
wuko233 2026-03-29 00:22:32 +08:00
parent eba278904f
commit 226c73711a
5 changed files with 86 additions and 0 deletions

22
cmd/main.go Normal file
View File

@ -0,0 +1,22 @@
package main
import (
"fmt"
"log"
"sysmonitord/internal/config"
)
func main() {
configPath := "./config.yaml"
cfg, err := config.LoadConfig(configPath)
if err != nil {
log.Fatalf("加载配置失败: %v", err)
}
fmt.Println("加载配置成功:")
fmt.Printf("审计配置: %+v\n", cfg.Audit)
fmt.Printf("扫描配置: %+v\n", cfg.Scanner)
fmt.Printf("审计服务器地址:%s:%d\n", cfg.Audit.Server, cfg.Audit.Port)
}

15
config.yaml Normal file
View File

@ -0,0 +1,15 @@
server:
host: "127.0.0.1"
port: 8080
audit:
enabled: true
server: "192.168.1.100"
port: 9000
buffer_size: 1000
scanner:
file:
exclude_paths:
- /proc
- /sys

5
go.mod Normal file
View File

@ -0,0 +1,5 @@
module sysmonitord
go 1.26.1
require gopkg.in/yaml.v3 v3.0.1 // indirect

3
go.sum Normal file
View File

@ -0,0 +1,3 @@
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

41
internal/config/config.go Normal file
View File

@ -0,0 +1,41 @@
package config
import (
"fmt"
"os"
"gopkg.in/yaml.v3"
)
type Config struct {
Audit AuditConfig `yaml:"audit"`
Scanner ScannerConfig `yaml:"scanner"`
}
type AuditConfig struct {
Enabled bool `yaml:"enabled"`
Server string `yaml:"server"`
Port int `yaml:"port"`
BufferSize int `yaml:"buffer_size"`
}
type ScannerConfig struct {
File FileScannerConfig `yaml:"file"`
}
type FileScannerConfig struct {
ExcludePaths []string `yaml:"exclude_paths"`
}
func LoadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("无法读取配置文件: %w", err)
}
var cfg Config
if err := yaml.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("无法解析配置文件: %w", err)
}
return &cfg, nil
}