feat: validation, postgress connection,

This commit is contained in:
2026-03-12 11:23:18 +01:00
parent abf2db2798
commit 56fa7b6c21
15 changed files with 269 additions and 37 deletions
@@ -2,6 +2,8 @@ package data
import (
"time"
"greenlight.debuggingjon.dev/internal/validator"
)
type Movie struct {
@@ -13,3 +15,20 @@ type Movie struct {
Genres []string `json:"genres,omitempty"` // Add the omitempty directive
Version int32 `json:"version"`
}
func ValidateMovie(v *validator.Validator, movie *Movie) {
v.Check(movie.Title != "", "title", "must be provided")
v.Check(len(movie.Title) <= 500, "title", "must not be more than 500 bytes long")
v.Check(movie.Year != 0, "year", "must be provided")
v.Check(movie.Year >= 1888, "year", "must be greater than 1888")
v.Check(movie.Year <= int32(time.Now().Year()), "year", "must not be in the future")
v.Check(movie.Runtime != 0, "runtime", "must be provided")
v.Check(movie.Runtime > 0, "runtime", "must be a positive integer")
v.Check(movie.Genres != nil, "genres", "must be provided")
v.Check(len(movie.Genres) >= 1, "genres", "must contain at least 1 genre")
v.Check(len(movie.Genres) <= 5, "genres", "must not contain more than 5 genres")
v.Check(validator.Unique(movie.Genres), "genres", "must not contain duplicate values")
}
@@ -1,14 +1,59 @@
package data
import (
"errors"
"fmt"
"strconv"
"strings"
)
// Define an error that our UnmarshalJSON() method can return if we're unable to parse
// or convert the JSON string successfully.
var ErrInvalidRuntimeFormat = errors.New("invalid runtime format")
// Declare a custom Runtime type, which has the underlying type int32 (the same as our
// Movie struct field).
type Runtime int32
// Implement a UnmarshalJSON() method on the Runtime type so that it satisfies the
// json.Unmarshaler interface. IMPORTANT: Because UnmarshalJSON() needs to modify the
// receiver (our Runtime type), we must use a pointer receiver for this to work
// correctly. Otherwise, we will only be modifying a copy (which is then discarded when
// this method returns).
func (r *Runtime) UnmarshalJSON(jsonValue []byte) error {
// We expect that the incoming JSON value will be a string in the format
// "<runtime> mins", and the first thing we need to do is remove the surrounding
// double-quotes from this string. If we can't unquote it, then we return the
// ErrInvalidRuntimeFormat error.
unquotedJSONValue, err := strconv.Unquote(string(jsonValue))
if err != nil {
return ErrInvalidRuntimeFormat
}
// Split the string to isolate the part containing the number.
parts := strings.Split(unquotedJSONValue, " ")
// Sanity check the parts of the string to make sure it was in the expected format.
// If it isn't, we return the ErrInvalidRuntimeFormat error again.
if len(parts) != 2 || parts[1] != "mins" {
return ErrInvalidRuntimeFormat
}
// Otherwise, parse the string containing the number into an int32. Again, if this
// fails return the ErrInvalidRuntimeFormat error.
i, err := strconv.ParseInt(parts[0], 10, 32)
if err != nil {
return ErrInvalidRuntimeFormat
}
// Convert the int32 to a Runtime type and assign this to the receiver. Note that we use
// use the * operator to deference the receiver (which is a pointer to a Runtime
// type) in order to set the underlying value of the pointer.
*r = Runtime(i)
return nil
}
// Implement a MarshalJSON() method on the Runtime type so that it satisfies the
// json.Marshaler interface. This should return the JSON-encoded value for the movie
// runtime (in our case, it will return a string in the format "<runtime> mins").
@@ -0,0 +1,66 @@
package validator
import (
"regexp"
"slices"
)
// Declare a regular expression for sanity checking the format of email addresses (we'll
// use this later in the book). If you're interested, this regular expression pattern is
// taken from https://html.spec.whatwg.org/#valid-e-mail-address. Note: if you're
// reading this in PDF or EPUB format and cannot see the full pattern, please see the
// note further down the page.
var (
EmailRX = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
)
// Define a new Validator type which contains a map of validation errors.
type Validator struct {
Errors map[string]string
}
// New is a helper which creates a new Validator instance with an empty errors map.
func New() *Validator {
return &Validator{Errors: make(map[string]string)}
}
// Valid returns true if the errors map doesn't contain any entries.
func (v *Validator) Valid() bool {
return len(v.Errors) == 0
}
// AddError adds an error message to the map (so long as no entry already exists for
// the given key).
func (v *Validator) AddError(key, message string) {
if _, exists := v.Errors[key]; !exists {
v.Errors[key] = message
}
}
// Check adds an error message to the map only if a validation check is not 'ok'.
func (v *Validator) Check(ok bool, key, message string) {
if !ok {
v.AddError(key, message)
}
}
// In returns true if a specific value is in a list of strings.
func In(value string, list ...string) bool {
return slices.Contains(list, value)
}
// Matches returns true if a string value matches a specific regexp pattern.
func Matches(value string, rx *regexp.Regexp) bool {
return rx.MatchString(value)
}
// Unique returns true if all string values in a slice are unique.
func Unique(values []string) bool {
uniqueValues := make(map[string]bool, 5)
for _, value := range values {
uniqueValues[value] = true
}
return len(values) == len(uniqueValues)
}