Initial commit: gocarlog project — Milestones 1-10 completed
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gocarlog/internal/middleware"
|
||||
"gocarlog/internal/model"
|
||||
)
|
||||
|
||||
// HandleConsumption handles GET /api/vehicles/:id/consumption
|
||||
func HandleConsumption(w http.ResponseWriter, r *http.Request) {
|
||||
// Extract ID from URL path: /api/vehicles/:id/consumption
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
// parts: ["api", "vehicles", ":id", "consumption"]
|
||||
if len(parts) < 4 {
|
||||
middleware.WriteError(w, http.StatusBadRequest, "invalid path")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.Atoi(parts[2])
|
||||
if err != nil {
|
||||
middleware.WriteError(w, http.StatusBadRequest, "invalid vehicle ID")
|
||||
return
|
||||
}
|
||||
|
||||
dateFrom := r.URL.Query().Get("date_from")
|
||||
dateTo := r.URL.Query().Get("date_to")
|
||||
|
||||
var dateFromPtr, dateToPtr *string
|
||||
if dateFrom != "" {
|
||||
dateFromPtr = &dateFrom
|
||||
}
|
||||
if dateTo != "" {
|
||||
dateToPtr = &dateTo
|
||||
}
|
||||
|
||||
db := r.Context().Value(middleware.DbKey).(*sql.DB)
|
||||
result, err := model.GetConsumption(db, id, dateFromPtr, dateToPtr)
|
||||
if err != nil {
|
||||
log.Printf("error getting consumption: %v", err)
|
||||
middleware.WriteError(w, http.StatusInternalServerError, "failed to get consumption data")
|
||||
return
|
||||
}
|
||||
|
||||
middleware.WriteJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"success": true,
|
||||
"data": result,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user