63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
package product
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strings"
|
|
|
|
tool "eino-project/internal/tools/product"
|
|
)
|
|
|
|
type Handler struct {
|
|
tool tool.Tool
|
|
}
|
|
|
|
func NewHandler(t tool.Tool) *Handler { return &Handler{tool: t} }
|
|
|
|
type queryRequest struct {
|
|
Query struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
} `json:"query"`
|
|
Page int `json:"page,omitempty"`
|
|
Size int `json:"size,omitempty"`
|
|
}
|
|
|
|
type queryResponse struct {
|
|
Items []*tool.Product `json:"items"`
|
|
Source string `json:"source"`
|
|
Count int `json:"count"`
|
|
}
|
|
|
|
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
var req queryRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
var items []*tool.Product
|
|
src := ""
|
|
|
|
if id := strings.TrimSpace(req.Query.ID); id != "" {
|
|
if p, _ := h.tool.GetByID(r.Context(), id); p != nil {
|
|
items = append(items, p)
|
|
}
|
|
src = "id"
|
|
} else if name := strings.TrimSpace(req.Query.Name); name != "" {
|
|
res, _ := h.tool.SearchByName(r.Context(), name)
|
|
items = res
|
|
src = "name"
|
|
} else {
|
|
http.Error(w, "query.id or query.name required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(&queryResponse{Items: items, Source: src, Count: len(items)})
|
|
} |