Files
wails-epic/internal/config/config.go
hu xiaotong 0246bc7060 init
2025-07-02 16:12:52 +08:00

120 lines
2.5 KiB
Go

package config
import (
"encoding/json"
"os"
"path/filepath"
)
type Config struct {
App AppConfig `json:"app"`
Capture CaptureConfig `json:"capture"`
Parser ParserConfig `json:"parser"`
Log LogConfig `json:"log"`
}
type AppConfig struct {
Name string `json:"name"`
Version string `json:"version"`
Debug bool `json:"debug"`
}
type CaptureConfig struct {
DefaultFilter string `json:"default_filter"`
DefaultTimeout int `json:"default_timeout"`
BufferSize int `json:"buffer_size"`
MaxPacketSize int `json:"max_packet_size"`
}
type ParserConfig struct {
MaxDataSize int `json:"max_data_size"`
EnableValidation bool `json:"enable_validation"`
}
type LogConfig struct {
Level string `json:"level"`
File string `json:"file"`
MaxSize int `json:"max_size"`
MaxBackups int `json:"max_backups"`
MaxAge int `json:"max_age"`
Compress bool `json:"compress"`
}
// Load 加载配置文件
func Load() (*Config, error) {
configPath := getConfigPath()
// 如果配置文件不存在,创建默认配置
if _, err := os.Stat(configPath); os.IsNotExist(err) {
if err := createDefaultConfig(configPath); err != nil {
return nil, err
}
}
file, err := os.Open(configPath)
if err != nil {
return nil, err
}
defer file.Close()
var config Config
if err := json.NewDecoder(file).Decode(&config); err != nil {
return nil, err
}
return &config, nil
}
func getConfigPath() string {
homeDir, err := os.UserHomeDir()
if err != nil {
return "config.json"
}
return filepath.Join(homeDir, ".equipment-analyzer", "config.json")
}
func createDefaultConfig(path string) error {
config := &Config{
App: AppConfig{
Name: "equipment-analyzer",
Version: "1.0.0",
Debug: false,
},
Capture: CaptureConfig{
DefaultFilter: "tcp and ( port 5222 or port 3333 )",
DefaultTimeout: 3000,
BufferSize: 1600,
MaxPacketSize: 65535,
},
Parser: ParserConfig{
MaxDataSize: 1024 * 1024, // 1MB
EnableValidation: true,
},
Log: LogConfig{
Level: "info",
File: "equipment-analyzer.log",
MaxSize: 100, // MB
MaxBackups: 3,
MaxAge: 28, // days
Compress: true,
},
}
// 创建目录
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
// 写入配置文件
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
return encoder.Encode(config)
}