package handlers import ( "encoding/json" "fmt" "net/http" "time" "licensing-cotton/internal/database" "licensing-cotton/internal/logger" "licensing-cotton/internal/models" ) // 创建/更新设备 func HandleCreateOrUpdateDevice(w http.ResponseWriter, r *http.Request) { if !isAdminRequest(w, r) { return } var req struct { DeviceID string `json:"device_id"` Expiration string `json:"expiration"` // RFC3339 } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "解析请求失败", http.StatusBadRequest) return } exp, err := time.Parse(time.RFC3339, req.Expiration) if err != nil { http.Error(w, "时间格式错误", http.StatusBadRequest) return } // 先查是否存在 var id int64 err = database.DB.QueryRow(`SELECT id FROM devices WHERE device_id = ?`, req.DeviceID). Scan(&id) if err != nil { // 如果设备不存在,插入 if err.Error() == "sql: no rows in result set" { _, err = database.DB.Exec(`INSERT INTO devices(device_id, expiration) VALUES (?, ?)`, req.DeviceID, exp) if err != nil { http.Error(w, "创建设备失败", http.StatusInternalServerError) return } fmt.Fprintf(w, "设备 %s 创建成功\n", req.DeviceID) return } http.Error(w, "查询设备失败", http.StatusInternalServerError) return } // 若已存在,更新 _, err = database.DB.Exec(`UPDATE devices SET expiration=? WHERE device_id=?`, exp, req.DeviceID) if err != nil { http.Error(w, "更新设备失败", http.StatusInternalServerError) return } fmt.Fprintf(w, "设备 %s 已更新到期时间: %v\n", req.DeviceID, exp) } func HandleListDevices(w http.ResponseWriter, r *http.Request) { if !isAdminRequest(w, r) { return } rows, err := database.DB.Query(`SELECT id, device_id, expiration FROM devices`) if err != nil { logger.Error("查询设备列表失败: %v", err) http.Error(w, "查询失败", http.StatusInternalServerError) return } defer rows.Close() devices := []models.Device{} for rows.Next() { var d models.Device if err := rows.Scan(&d.ID, &d.DeviceID, &d.Expiration); err != nil { logger.Error("扫描设备记录失败: %v", err) http.Error(w, "解析记录失败", http.StatusInternalServerError) return } devices = append(devices, d) } // 检查是否有行扫描错误 if err = rows.Err(); err != nil { logger.Error("行扫描错误: %v", err) http.Error(w, "读取记录失败", http.StatusInternalServerError) return } logger.Debug("返回设备列表,共 %d 个设备", len(devices)) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(devices) }