Adding readString, readInt and readCSV helper functions
This commit is contained in:
@@ -5,8 +5,10 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"greenlight.craftr.fr/internal/validator"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
@@ -153,3 +155,52 @@ func (app *application) readJSON(w http.ResponseWriter, r *http.Request, dst any
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// readString : returns a string value from the query string, or the provided default value if no matching key could be found
|
||||
func (app *application) readString(qs url.Values, key string, defaultValue string) string {
|
||||
// Extract the value for a give key from the query string. If no key exists, this will return the empty string ""
|
||||
s := qs.Get(key)
|
||||
|
||||
// If no key exists (or the value is empty) then return the default value
|
||||
if s == "" {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// Otherwise, return the string
|
||||
return s
|
||||
}
|
||||
|
||||
// readCSV : reads a string value from the query string and then splits it into a slice on the comma character. If no matching key could be found, it returns the provided default value
|
||||
func (app *application) readCSV(qs url.Values, key string, defaultValue []string) []string {
|
||||
// Extract the value from the query string
|
||||
csv := qs.Get(key)
|
||||
|
||||
// If no key exists (or the value is empty) then returns the default value
|
||||
if csv == "" {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// Otherwise parse the value into a []string slice and return it
|
||||
return strings.Split(csv, ",")
|
||||
}
|
||||
|
||||
// readInt : reads a string value from the query string and converts it to an integer before returning. If no matching key could be found; it returns the provided default value. If the value couldn't be converted to an integer, then we record an error message in the provided Validator instance.
|
||||
func (app *application) readInt(qs url.Values, key string, defaultValue int, v *validator.Validator) int {
|
||||
// Extract the value from the query string
|
||||
s := qs.Get(key)
|
||||
|
||||
// If no key exists (or the value is empty) then return the default value
|
||||
if s == "" {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// Try to convert the value to an int. If this fails, add an error message to the validator instance and return the default value
|
||||
i, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
v.AddError(key, "must be an integer value")
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// Otherwise, return the converted integer value
|
||||
return i
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user