176 lines
4.3 KiB
Go
176 lines
4.3 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"gardomatic.kleiax.de/internal/platform/validate"
|
|
"github.com/julienschmidt/httprouter"
|
|
)
|
|
|
|
func (app *application) readIDParam(r *http.Request) (int, error) {
|
|
return app.readNamedIDParam(r, "id")
|
|
}
|
|
|
|
func (app *application) readNamedIDParam(r *http.Request, name string) (int, error) {
|
|
params := httprouter.ParamsFromContext(r.Context())
|
|
id, err := strconv.Atoi(params.ByName(name))
|
|
if err != nil || id < 1 {
|
|
return 0, errors.New("invalid id parameter")
|
|
}
|
|
|
|
return id, nil
|
|
}
|
|
|
|
func (app *application) readGardenIDParam(r *http.Request) (int, error) {
|
|
params := httprouter.ParamsFromContext(r.Context())
|
|
|
|
id, err := strconv.Atoi(params.ByName("gardenID"))
|
|
if err != nil || id < 1 {
|
|
return 0, errors.New("invalid garden id parameter")
|
|
}
|
|
|
|
return id, nil
|
|
}
|
|
|
|
type envelope map[string]any
|
|
|
|
func (app *application) writeJSON(w http.ResponseWriter, status int, data envelope, headers http.Header) error {
|
|
js, err := json.MarshalIndent(data, "", "\t")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
js = append(js, '\n')
|
|
|
|
for key, values := range headers {
|
|
for _, value := range values {
|
|
w.Header().Add(key, value)
|
|
}
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
w.Write(js)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (app *application) readJSON(w http.ResponseWriter, r *http.Request, dst any) error {
|
|
r.Body = http.MaxBytesReader(w, r.Body, 2_097_152)
|
|
|
|
dec := json.NewDecoder(r.Body)
|
|
dec.DisallowUnknownFields()
|
|
|
|
err := dec.Decode(dst)
|
|
if err != nil {
|
|
var syntaxError *json.SyntaxError
|
|
var unmarshalTypeError *json.UnmarshalTypeError
|
|
var invalidUnmarshalError *json.InvalidUnmarshalError
|
|
var maxBytesError *http.MaxBytesError
|
|
|
|
switch {
|
|
case errors.As(err, &syntaxError):
|
|
return fmt.Errorf("body contains badly-formed JSON (at character %d)", syntaxError.Offset)
|
|
|
|
case errors.Is(err, io.ErrUnexpectedEOF):
|
|
return errors.New("body contains badly-formed JSON")
|
|
|
|
case errors.As(err, &unmarshalTypeError):
|
|
if unmarshalTypeError.Field != "" {
|
|
return fmt.Errorf("body contains incorrect JSON type for field %q", unmarshalTypeError.Field)
|
|
}
|
|
return fmt.Errorf("body contains incorrect JSON type (at character %d)", unmarshalTypeError.Offset)
|
|
|
|
case errors.Is(err, io.EOF):
|
|
return errors.New("body must not be empty")
|
|
|
|
case strings.HasPrefix(err.Error(), "json: unknown field "):
|
|
fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ")
|
|
return fmt.Errorf("body contains unknown key %s", fieldName)
|
|
|
|
case errors.As(err, &maxBytesError):
|
|
return fmt.Errorf("body must not be larger than %d bytes", maxBytesError.Limit)
|
|
|
|
case errors.As(err, &invalidUnmarshalError):
|
|
panic(err)
|
|
|
|
default:
|
|
return err
|
|
}
|
|
}
|
|
|
|
err = dec.Decode(&struct{}{})
|
|
if !errors.Is(err, io.EOF) {
|
|
return errors.New("body must only contain a single JSON value")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func validateImageData(v *validate.Validator, imageData string) {
|
|
if imageData == "" {
|
|
return
|
|
}
|
|
v.Check(len(imageData) <= 1_500_000, "image_data", "must not be larger than 1.5 MB")
|
|
v.Check(strings.HasPrefix(imageData, "data:image/jpeg;base64,") || strings.HasPrefix(imageData, "data:image/png;base64,") || strings.HasPrefix(imageData, "data:image/webp;base64,"), "image_data", "must be a JPEG, PNG or WebP image")
|
|
}
|
|
|
|
//lint:ignore U1000 retained for the upcoming list filters
|
|
func (app *application) readString(qs url.Values, key string, defaultValue string) string {
|
|
s := qs.Get(key)
|
|
|
|
if s == "" {
|
|
return defaultValue
|
|
}
|
|
|
|
return s
|
|
}
|
|
|
|
//lint:ignore U1000 retained for the upcoming list filters
|
|
func (app *application) readCSV(qs url.Values, key string, defaultValue []string) []string {
|
|
csv := qs.Get(key)
|
|
|
|
if csv == "" {
|
|
return defaultValue
|
|
}
|
|
|
|
return strings.Split(csv, ",")
|
|
}
|
|
|
|
//lint:ignore U1000 retained for the upcoming pagination support
|
|
func (app *application) readInt(qs url.Values, key string, defaultValue int, v *validate.Validator) int {
|
|
s := qs.Get(key)
|
|
|
|
if s == "" {
|
|
return defaultValue
|
|
}
|
|
|
|
i, err := strconv.Atoi(s)
|
|
if err != nil {
|
|
v.AddError(key, "must be an integer value")
|
|
return defaultValue
|
|
}
|
|
|
|
return i
|
|
}
|
|
|
|
func (app *application) background(fn func()) {
|
|
app.wg.Go(func() {
|
|
defer func() {
|
|
pv := recover()
|
|
if pv != nil {
|
|
app.logger.Error(fmt.Sprintf("%v", pv))
|
|
}
|
|
}()
|
|
|
|
fn()
|
|
})
|
|
}
|