daShangDao_kfz_goods_pricing/internal/handler/token_handler.go

240 lines
7.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handler
import (
"encoding/json"
"log"
"net/http"
"strconv"
"kfz-goods-pricing/internal/repository"
)
// TokenHandler Token处理器
type TokenHandler struct {
tokenRepo *repository.TokenRepository
}
// NewTokenHandler 创建Token处理器实例
func NewTokenHandler(tokenRepo *repository.TokenRepository) *TokenHandler {
return &TokenHandler{
tokenRepo: tokenRepo,
}
}
// TokenResponse Token响应结构
type TokenResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// TokenInput Token输入结构
type TokenInput struct {
LoginName string `json:"login_name"`
Username string `json:"username"`
Password string `json:"password"`
Token string `json:"token"`
}
// BatchAddTokens 批量添加TokenJSON数组: [{"username":"","token":""},...]
func (h *TokenHandler) BatchAddTokens(w http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
clientIP = forwarded
}
if r.Method == http.MethodOptions {
return
}
var inputs []TokenInput
if err := json.NewDecoder(r.Body).Decode(&inputs); err != nil {
log.Printf("[Token/BatchAdd] 请求体解析失败: err=%v, clientIP=%s", err, clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 400, Message: "invalid request body"})
return
}
log.Printf("[Token/BatchAdd] 收到请求: clientIP=%s, tokenCount=%d", clientIP, len(inputs))
if len(inputs) == 0 {
log.Printf("[Token/BatchAdd] 空数组: clientIP=%s", clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 400, Message: "empty array"})
return
}
// 逐条插入
var failed []TokenInput
for i, input := range inputs {
if input.Username == "" || input.Token == "" {
log.Printf("[Token/BatchAdd] 第%d条数据不完整(username或token为空), 跳过", i+1)
failed = append(failed, input)
continue
}
id, err := h.tokenRepo.Insert(input.LoginName, input.Username, input.Password, input.Token, true)
if err != nil {
log.Printf("[Token/BatchAdd] 第%d条插入失败: username=%s, 错误=%v", i+1, input.Username, err)
failed = append(failed, input)
} else {
log.Printf("[Token/BatchAdd] 第%d条插入成功: id=%d, login_name=%s, username=%s", i+1, id, input.LoginName, input.Username)
}
}
w.Header().Set("Content-Type", "application/json")
if len(failed) > 0 {
log.Printf("[Token/BatchAdd] 部分成功: successCount=%d, failCount=%d, clientIP=%s", len(inputs)-len(failed), len(failed), clientIP)
json.NewEncoder(w).Encode(TokenResponse{
Code: 207,
Message: "partial success",
Data: map[string]interface{}{"failed": failed},
})
return
}
log.Printf("[Token/BatchAdd] 全部成功: count=%d, clientIP=%s", len(inputs), clientIP)
json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success"})
}
// GetAllTokens 查询所有Token
func (h *TokenHandler) GetAllTokens(w http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
clientIP = forwarded
}
log.Printf("[Token/GetAll] 收到请求: clientIP=%s", clientIP)
if r.Method == http.MethodOptions {
return
}
records, err := h.tokenRepo.GetAll()
if err != nil {
log.Printf("[Token/GetAll] 查询失败: err=%v, clientIP=%s", err, clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 500, Message: err.Error()})
return
}
log.Printf("[Token/GetAll] 查询成功: count=%d, clientIP=%s", len(records), clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success", Data: records})
}
// DeleteToken 删除Token
func (h *TokenHandler) DeleteToken(w http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
clientIP = forwarded
}
log.Printf("[Token/Delete] 收到请求: clientIP=%s", clientIP)
if r.Method == http.MethodOptions {
return
}
// 解析 form-data 或 URL 参数
r.ParseMultipartForm(32 << 20)
r.ParseForm()
idStr := r.PostForm.Get("id")
if idStr == "" {
// 尝试从URL获取
idStr = r.URL.Query().Get("id")
}
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
log.Printf("[Token/Delete] 参数id无效: id=%s, clientIP=%s", idStr, clientIP)
http.Error(w, "invalid id", http.StatusBadRequest)
return
}
err = h.tokenRepo.Delete(id)
if err != nil {
log.Printf("[Token/Delete] 删除失败: id=%d, 错误=%v, 来源IP: %s", id, err, clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 500, Message: err.Error()})
return
}
log.Printf("[Token/Delete] 删除成功: id=%d, 来源IP: %s", id, clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success"})
}
// UpdateToken 修改Token
func (h *TokenHandler) UpdateToken(w http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
clientIP = forwarded
}
log.Printf("[Token/Update] 收到请求: clientIP=%s", clientIP)
if r.Method == http.MethodOptions {
return
}
// 解析 form-data
r.ParseMultipartForm(32 << 20)
r.ParseForm()
idStr := r.PostForm.Get("id")
loginName := r.PostForm.Get("login_name")
username := r.PostForm.Get("username")
password := r.PostForm.Get("password")
token := r.PostForm.Get("token")
isEnableStr := r.PostForm.Get("is_enable")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
log.Printf("[Token/Update] 参数id无效: id=%s, clientIP=%s", idStr, clientIP)
http.Error(w, "invalid id", http.StatusBadRequest)
return
}
isEnable := true
if isEnableStr == "0" || isEnableStr == "false" {
isEnable = false
}
log.Printf("[Token/Update] 更新: id=%d, login_name=%s, username=%s, is_enable=%v, 来源IP: %s", id, loginName, username, isEnable, clientIP)
err = h.tokenRepo.Update(id, loginName, username, password, token, isEnable)
if err != nil {
log.Printf("[Token/Update] 更新失败: id=%d, 错误=%v, 来源IP: %s", id, err, clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 500, Message: err.Error()})
return
}
log.Printf("[Token/Update] 更新成功: id=%d, 来源IP: %s", id, clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success"})
}
// GetEnabledTokens 获取所有启用的Token
func (h *TokenHandler) GetEnabledTokens(w http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
clientIP = forwarded
}
log.Printf("[Token/GetEnabled] 收到请求: clientIP=%s", clientIP)
if r.Method == http.MethodOptions {
return
}
records, err := h.tokenRepo.GetEnabledTokens()
if err != nil {
log.Printf("[Token/GetEnabled] 查询失败: err=%v, clientIP=%s", err, clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 500, Message: err.Error()})
return
}
log.Printf("[Token/GetEnabled] 查询成功: count=%d, clientIP=%s", len(records), clientIP)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success", Data: records})
}