From 041d302a791aef59291a5d98f413ef81428518c3 Mon Sep 17 00:00:00 2001 From: Maxime Delporte Date: Tue, 11 Nov 2025 10:43:34 +0100 Subject: [PATCH] Creating listMoviesHandler and adding /v1/movies GET endpoint to use it. --- cmd/api/movies.go | 37 +++++++++++++++++++++++++++++++++++++ cmd/api/routes.go | 2 ++ 2 files changed, 39 insertions(+) diff --git a/cmd/api/movies.go b/cmd/api/movies.go index 4d6303d..cf95145 100644 --- a/cmd/api/movies.go +++ b/cmd/api/movies.go @@ -202,3 +202,40 @@ func (app *application) deleteMovieHandler(w http.ResponseWriter, r *http.Reques app.serverErrorResponse(w, r, err) } } + +func (app *application) listMoviesHandler(w http.ResponseWriter, r *http.Request) { + // To keep things consistent with our other handlers, we'll define an input struct to hold the expected values from the request query string + var input struct { + Title string + Genres []string + Page int + PageSize int + Sort string + } + + // Initialize a new Validator instance + v := validator.New() + + // Call r.URL.Query() to get the url.Values map containing the query string data. + qs := r.URL.Query() + + // Use our helpers to extract the title and genres query strings values, falling back to defaults of an empty string and an empty slice respectively if they are not provided by the client. + input.Title = app.readString(qs, "title", "") + input.Genres = app.readCSV(qs, "genres", []string{}) + + // Get the page and page_size query string values as integers. Notice that we set the default page value to 1 and default page_size to 20, and that we pass the validator instance as the final argument here + input.Page = app.readInt(qs, "page", 1, v) + input.PageSize = app.readInt(qs, "page_size", 20, v) + + // Extract the sort query string value, falling back to "id" if it is not provided by the client (which will imply an ascending sort on movie ID) + input.Sort = app.readString(qs, "sort", "id") + + // Check the Validator instance for any errors and use the failedValidationResponse() helper to send the client a response if necessary + if !v.Valid() { + app.failedValidationResponse(w, r, v.Errors) + return + } + + // Dump the contents of the input struct in a HTTP response + fmt.Fprintf(w, "%+v\n", input) +} diff --git a/cmd/api/routes.go b/cmd/api/routes.go index f066228..a4126e6 100644 --- a/cmd/api/routes.go +++ b/cmd/api/routes.go @@ -22,6 +22,8 @@ func (app *application) routes() http.Handler { respectively. */ router.HandlerFunc(http.MethodGet, "/v1/healthcheck", app.healthcheckHandler) + + router.HandlerFunc(http.MethodGet, "/v1/movies", app.listMoviesHandler) router.HandlerFunc(http.MethodPost, "/v1/movies", app.createMovieHandler) router.HandlerFunc(http.MethodGet, "/v1/movies/:id", app.showMovieHandler) router.HandlerFunc(http.MethodPatch, "/v1/movies/:id", app.updateMovieHandler)