- Remove duplicate calc structs, use model.CalcXxx - Replace log.Printf with logger in recommend handler - Remove dead code (unused var, dummy imports) - Clean up response helpers - Add api/ package with route registration Co-Authored-By: Claude <noreply@anthropic.com>
76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package handler
|
|
|
|
import (
|
|
"database/sql"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"floorvisualizer/internal/repository"
|
|
)
|
|
|
|
func Articles(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// /articles/{id} — detail
|
|
idStr := strings.TrimPrefix(r.URL.Path, "/articles/")
|
|
if idStr != "" && idStr != r.URL.Path {
|
|
id, err := strconv.Atoi(idStr)
|
|
if err != nil {
|
|
writeJSON(w, 400, map[string]string{"error": "invalid article id"})
|
|
return
|
|
}
|
|
article, err := repository.GetArticleByID(db, id)
|
|
if err != nil {
|
|
writeJSON(w, 404, map[string]string{"error": "article not found"})
|
|
return
|
|
}
|
|
writeJSON(w, 200, article)
|
|
return
|
|
}
|
|
|
|
// /articles — list
|
|
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
|
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
|
|
|
articles, total, err := repository.ListArticles(db, page, limit)
|
|
if err != nil {
|
|
writeJSON(w, 500, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
effectiveLimit := limit
|
|
if effectiveLimit <= 0 {
|
|
effectiveLimit = 10
|
|
}
|
|
totalPages := 0
|
|
if total > 0 {
|
|
totalPages = (total + effectiveLimit - 1) / effectiveLimit
|
|
}
|
|
|
|
writeJSON(w, 200, map[string]interface{}{
|
|
"articles": articles,
|
|
"total": total,
|
|
"page": page,
|
|
"limit": effectiveLimit,
|
|
"total_pages": totalPages,
|
|
})
|
|
}
|
|
}
|
|
|
|
func ArticleRecommend(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
count := 6
|
|
if c, err := strconv.Atoi(r.URL.Query().Get("count")); err == nil && c > 0 && c <= 20 {
|
|
count = c
|
|
}
|
|
articles, err := repository.RandomArticles(db, count)
|
|
if err != nil {
|
|
writeJSON(w, 500, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]interface{}{
|
|
"articles": articles,
|
|
"total": len(articles),
|
|
})
|
|
}
|
|
}
|