daShangDao_kfz_goods_pricing/internal/handler/goods_handler.go

96 lines
3.1 KiB
Go

package handler
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"strconv"
"kfz-goods-pricing/internal/service"
)
// GoodsHandler 商品处理器
type GoodsHandler struct {
goodsService *service.GoodsService
}
// NewGoodsHandler 创建商品处理器实例
func NewGoodsHandler(goodsService *service.GoodsService) *GoodsHandler {
return &GoodsHandler{
goodsService: goodsService,
}
}
// QueryGoods 查询商品接口
func (h *GoodsHandler) QueryGoods(w http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
clientIP = forwarded
}
log.Printf("[QueryGoods] 收到请求, 来源IP: %s, Method: %s", clientIP, r.Method)
// 只支持POST请求
if r.Method != http.MethodPost {
log.Printf("[QueryGoods] 方法不允许: %s, 来源IP: %s", r.Method, clientIP)
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 读取原始body用于调试
bodyBytes, _ := io.ReadAll(r.Body)
bodyStr := string(bodyBytes)
log.Printf("[QueryGoods] 原始请求 Body: [%s], Content-Type: [%s]", bodyStr, r.Header.Get("Content-Type"))
// 重新创建body供ParseForm使用
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
// 解析参数 - ParseMultipartForm 同时支持 form-data 和 x-www-form-urlencoded
if err := r.ParseMultipartForm(32 << 20); err != nil {
// 尝试纯表单解析
if err := r.ParseForm(); err != nil {
log.Printf("[QueryGoods] 参数解析失败: %v, 来源IP: %s", err, clientIP)
http.Error(w, "Invalid request form", http.StatusBadRequest)
return
}
}
isbn := r.FormValue("isbn")
bookName := r.FormValue("book_name")
author := r.FormValue("author")
publishing := r.FormValue("publishing")
outID := r.FormValue("out_id")
quality := r.FormValue("quality")
queryIndex := r.FormValue("query_index")
userID := r.FormValue("user_id")
placeholderDownPrice := r.FormValue("placeholder_down_price")
minShippingFee := r.FormValue("min_shipping_fee")
minPrice := r.FormValue("min_price")
log.Printf("[QueryGoods] 解析参数完成 - isbn=[%s], book_name=[%s], author=[%s], publishing=[%s], out_id=[%s], quality=[%s], query_index=[%s], user_id=[%s], placeholder_down_price=[%s], min_shipping_fee=[%s], min_price=[%s]",
isbn, bookName, author, publishing, outID, quality, queryIndex, userID, placeholderDownPrice, minShippingFee, minPrice)
var req service.QueryRequest
req.ISBN = isbn
req.BookName = bookName
req.Author = author
req.Publishing = publishing
req.OutID = outID
req.Quality = quality
req.QueryIndex, _ = strconv.Atoi(queryIndex)
req.UserID = userID
req.PlaceholderDownPrice, _ = strconv.ParseFloat(placeholderDownPrice, 64)
req.MinShippingFee, _ = strconv.ParseFloat(minShippingFee, 64)
req.MinPrice, _ = strconv.ParseFloat(minPrice, 64)
// 调用服务层
resp := h.goodsService.QueryGoods(&req)
log.Printf("[QueryGoods] 处理完成, ID=%d, Code=%d, Message=%s", resp.ID, resp.Code, resp.Message)
// 返回响应
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(resp)
}