package main import ( "log" "net/http" "strconv" "github.com/gin-gonic/gin" ) // MovieList 电影列表 func MovieList(c *gin.Context) { response := gin.H{ "code": http.StatusInternalServerError, "message": "An unexpected error occurred.", // Default error message "data": gin.H{"items": []Movie{}, "total": 0}, } categoryName := c.Query("category") // Expects category name like "15min", "30min", etc. var moviesToPaginate []Movie // Filter movies by category if a categoryName is provided if categoryName != "" { for _, m := range movies { // 'movies' is the global slice from initMovie() if m.TimeCategory == categoryName { moviesToPaginate = append(moviesToPaginate, m) } } } else { // If no category is specified, use all movies // The global 'movies' slice is already sorted by category, then duration. // So, if no category is given, pagination will occur over this pre-sorted list. moviesToPaginate = movies } // Pagination logic page := 0 // Default to page 1 (0-indexed internally) spage := c.Query("page") if spage != "" { p, err := strconv.Atoi(spage) if err != nil || p < 1 { // Page numbers should be 1 or greater log.Println("Invalid page number:", spage, err) response["code"] = http.StatusBadRequest response["message"] = "Invalid page number. Must be a positive integer." c.JSON(http.StatusBadRequest, response) // Send response immediately for bad input return } page = p - 1 // Convert to 0-indexed } limit := 12 // Default limit slimit := c.Query("limit") if slimit != "" { l, err := strconv.Atoi(slimit) if err != nil || l < 1 { // Limit should be positive log.Println("Invalid limit number:", slimit, err) response["code"] = http.StatusBadRequest response["message"] = "Invalid limit number. Must be a positive integer." c.JSON(http.StatusBadRequest, response) // Send response immediately return } limit = l } // Calculate start and end for slicing start := page * limit end := start + limit // Handle cases where the requested page is out of bounds if start >= len(moviesToPaginate) { // Requested page is beyond the available data, return empty list for items response["data"] = gin.H{ "items": []Movie{}, "total": len(moviesToPaginate), } response["code"] = http.StatusOK response["message"] = "Success" c.JSON(http.StatusOK, response) return } if end > len(moviesToPaginate) { end = len(moviesToPaginate) } // Prepare successful response data responseData := gin.H{ "items": moviesToPaginate[start:end], "total": len(moviesToPaginate), } response["code"] = http.StatusOK response["message"] = "Success" response["data"] = responseData c.JSON(http.StatusOK, response) }