feat(config): add UnmarshalJSON method and update NewProxyHandler parameter type

This commit is contained in:
wood chen 2024-11-17 08:15:29 +08:00
parent 74280e215e
commit c2ba3e4d3d
2 changed files with 44 additions and 30 deletions

View File

@ -1,5 +1,7 @@
package config package config
import "encoding/json"
type Config struct { type Config struct {
MAP map[string]PathConfig `json:"MAP"` // 改为使用PathConfig MAP map[string]PathConfig `json:"MAP"` // 改为使用PathConfig
Compression CompressionConfig `json:"Compression"` Compression CompressionConfig `json:"Compression"`
@ -28,27 +30,44 @@ type FixedPathConfig struct {
} }
// 添加一个辅助方法来处理字符串到 PathConfig 的转换 // 添加一个辅助方法来处理字符串到 PathConfig 的转换
func NewPathConfig(target interface{}) PathConfig { func (c *Config) UnmarshalJSON(data []byte) error {
switch v := target.(type) { // 创建一个临时结构来解析原始JSON
case string: type TempConfig struct {
// 简单字符串格式 MAP map[string]json.RawMessage `json:"MAP"`
return PathConfig{ Compression CompressionConfig `json:"Compression"`
DefaultTarget: v, FixedPaths []FixedPathConfig `json:"FixedPaths"`
} }
case map[string]interface{}:
// 完整配置格式 var temp TempConfig
config := PathConfig{ if err := json.Unmarshal(data, &temp); err != nil {
DefaultTarget: v["DefaultTarget"].(string), return err
} }
if extMap, ok := v["ExtensionMap"].(map[string]interface{}); ok {
config.ExtensionMap = make(map[string]string) // 初始化 MAP
for ext, target := range extMap { c.MAP = make(map[string]PathConfig)
config.ExtensionMap[ext] = target.(string)
// 处理每个路径配置
for key, raw := range temp.MAP {
// 尝试作为字符串解析
var strValue string
if err := json.Unmarshal(raw, &strValue); err == nil {
c.MAP[key] = PathConfig{
DefaultTarget: strValue,
} }
continue
} }
return config
default: // 如果不是字符串尝试作为PathConfig解析
// 处理异常情况 var pathConfig PathConfig
return PathConfig{} if err := json.Unmarshal(raw, &pathConfig); err != nil {
return err
} }
c.MAP[key] = pathConfig
}
// 复制其他字段
c.Compression = temp.Compression
c.FixedPaths = temp.FixedPaths
return nil
} }

View File

@ -21,15 +21,10 @@ type ProxyHandler struct {
pathMap map[string]config.PathConfig pathMap map[string]config.PathConfig
} }
func NewProxyHandler(pathMap map[string]interface{}) *ProxyHandler { // 修改参数类型
convertedMap := make(map[string]config.PathConfig) func NewProxyHandler(pathMap map[string]config.PathConfig) *ProxyHandler {
for path, target := range pathMap {
convertedMap[path] = config.NewPathConfig(target)
}
return &ProxyHandler{ return &ProxyHandler{
pathMap: convertedMap, pathMap: pathMap,
} }
} }