86 lines
2.2 KiB
Go
86 lines
2.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"licensing-cotton/internal/database"
|
|
"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 {
|
|
http.Error(w, "查询失败", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
|
|
var devices []models.Device
|
|
for rows.Next() {
|
|
var d models.Device
|
|
if err := rows.Scan(&d.ID, &d.DeviceID, &d.Expiration); err != nil {
|
|
http.Error(w, "解析记录失败", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
devices = append(devices, d)
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(devices)
|
|
}
|