Adding httprouter dependency to manage endpoints. Adding our routes to routes.go file facilitating endpoints management and adding POST /v1/movies and GET /v1/movies/:id endpoints. Updating main.go file removing ServeMux and add httprouter instead in app structure. Creating movies.go file to manage create and show movie endpoint.
This commit is contained in:
40
cmd/api/movies.go
Normal file
40
cmd/api/movies.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// "POST /v1/movies" endpoint.
|
||||
func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintln(w, "create a new movie")
|
||||
}
|
||||
|
||||
// "GET /v1/movies/:id"
|
||||
func (app *application) showMovieHandler(w http.ResponseWriter, r *http.Request) {
|
||||
/*
|
||||
When httprouter is parsing a request, any interpolated URL parameters will be
|
||||
stored in the request context. We can use the ParamsFromContext() function to
|
||||
retrieve a slice containing these parameter names and values.
|
||||
*/
|
||||
params := httprouter.ParamsFromContext(r.Context())
|
||||
|
||||
/*
|
||||
We can then use the ByName() method to get the value of the "id" parameter from
|
||||
the slice. In our project all movies will have a unique positive integer ID, but
|
||||
the value returned by ByName() is always a string. So we try to convert it to a
|
||||
base 1° integer (with a bit size of 64). If the parameter couldn't be converted,
|
||||
or is less than 1, we know the ID is invalid so we use the http.NotFound()
|
||||
func to return a 404 Not Found Response.
|
||||
*/
|
||||
id, err := strconv.ParseInt(params.ByName("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Otherwise, interpolate the movie ID in a placeholder response.
|
||||
fmt.Fprintf(w, "show the details of movie %d\n", id)
|
||||
}
|
||||
Reference in New Issue
Block a user