package handler import ( "encoding/json" "fmt" "log" "net/http" "strconv" "sync" "kfz-goods-pricing/internal/config" ) // ConfigHandler 配置处理器 type ConfigHandler struct { configPath string mu sync.Mutex } // NewConfigHandler 创建配置处理器实例 func NewConfigHandler(configPath string) *ConfigHandler { return &ConfigHandler{ configPath: configPath, } } // GetConfigPrice 获取配置(价格相关) func (h *ConfigHandler) GetConfigPrice(w http.ResponseWriter, r *http.Request) { h.mu.Lock() defer h.mu.Unlock() cfg, err := config.Load(h.configPath) if err != nil { log.Printf("[GetConfigPrice] 读取配置失败: %s", err.Error()) w.Header().Set("Content-Type", "application/json") w.Write([]byte(fmt.Sprintf(`{"code":500,"message":"读取配置失败: %s"}`, err.Error()))) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "code": 200, "message": "success", "data": cfg, }) } // SetConfigPrice 修改价格配置 func (h *ConfigHandler) SetConfigPrice(w http.ResponseWriter, r *http.Request) { r.ParseMultipartForm(32 << 20) newPrice := r.PostForm.Get("new_price") if newPrice == "" { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"code":400,"message":"new_price不能为空"}`)) return } val := 0.0 val, _ = strconv.ParseFloat(newPrice, 64) if val < 0 { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"code":400,"message":"new_price必须大于0"}`)) return } h.mu.Lock() defer h.mu.Unlock() cfg, err := config.Load(h.configPath) if err != nil { log.Printf("[SetConfigPrice] 读取配置失败: %s", err.Error()) w.Header().Set("Content-Type", "application/json") w.Write([]byte(fmt.Sprintf(`{"code":500,"message":"读取配置失败: %s"}`, err.Error()))) return } cfg.NewPrice = val if err := config.Save(h.configPath, cfg); err != nil { log.Printf("[SetConfigPrice] 保存配置失败: %s", err.Error()) w.Header().Set("Content-Type", "application/json") w.Write([]byte(fmt.Sprintf(`{"code":500,"message":"保存配置失败: %s"}`, err.Error()))) return } // 同步全局配置 config.SetGlobal(cfg) log.Printf("[SetConfigPrice] 配置更新成功: new_price=%.2f", cfg.NewPrice) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "code": 200, "message": "success", "data": cfg, }) }