76 lines
1.9 KiB
Go
76 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"greenlight.ergz/internal/data"
|
|
"greenlight.ergz/internal/validator"
|
|
)
|
|
|
|
func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Request) {
|
|
var input struct {
|
|
Title string `json:"title"`
|
|
Year int32 `json:"year"`
|
|
Runtime data.Runtime `json:"runtime"`
|
|
Genres []string `json:"genres"`
|
|
}
|
|
|
|
err := app.readJSON(w, r, &input)
|
|
if err != nil {
|
|
app.errorResponse(w, r, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
|
|
v := validator.New()
|
|
|
|
// validate title
|
|
v.Check(input.Title != "", "title", "must be provided")
|
|
v.Check(len(input.Title) <= 500, "title", "must not be more than 500 bytes")
|
|
|
|
// validate the year
|
|
v.Check(input.Year != 0, "year", "must be provided")
|
|
v.Check(input.Year >= 1888, "year", "must be greater than 1888")
|
|
v.Check(input.Year <= int32(time.Now().Year()), "year", "must not be in the future")
|
|
|
|
v.Check(input.Runtime != 0, "runtime", "must be provided")
|
|
v.Check(input.Runtime > 0, "runtime", "must be a positive integer")
|
|
|
|
v.Check(input.Genres != nil, "genres", "must be provided")
|
|
v.Check(len(input.Genres) >= 1, "genres", "at least one genre must be provided")
|
|
v.Check(len(input.Genres) <= 5, "genres", "no more than 5 genres can be provided")
|
|
v.Check(validator.Unique(input.Genres), "genres", "must not contain duplicate genre")
|
|
|
|
if !v.Valid() {
|
|
app.failedValidationResponse(w, r, v.Errors)
|
|
return
|
|
}
|
|
|
|
fmt.Fprintf(w, "%+v\n", input)
|
|
}
|
|
|
|
func (app *application) showMovieHandler(w http.ResponseWriter, r *http.Request) {
|
|
id, err := app.readIDParam(r)
|
|
if err != nil {
|
|
app.notFoundResponse(w, r)
|
|
return
|
|
}
|
|
|
|
movie := data.Movie{
|
|
ID: id,
|
|
CreatedAt: time.Now(),
|
|
Title: "Casablanca",
|
|
Runtime: 102,
|
|
Genres: []string{"drama", "romance", "war"},
|
|
Version: 1,
|
|
}
|
|
|
|
envelopedMovie := envelope{"movie": movie}
|
|
err = app.writeJSON(w, http.StatusOK, envelopedMovie, nil)
|
|
if err != nil {
|
|
app.serverErrorResponse(w, r, err)
|
|
}
|
|
|
|
}
|