| 1 | package httpx |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "strconv" |
| 6 | |
| 7 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 8 | ) |
| 9 | |
| 10 | // HandlerFunc is an HTTP handler that returns its error instead of writing it. |
| 11 | // The error goes to the client through Error, like every other error. Only |
| 12 | // return one before writing anything to w. |
| 13 | type HandlerFunc func(w http.ResponseWriter, r *http.Request) error |
| 14 | |
| 15 | func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 16 | if err := f(w, r); err != nil { |
| 17 | Error(w, r, err) |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | // QueryInt returns the query parameter key as an int, or def if it's absent. |
| 22 | // A value that isn't a whole number is a validation error on that parameter. |
| 23 | func QueryInt(r *http.Request, key string, def int) (int, error) { |
| 24 | s := r.URL.Query().Get(key) |
| 25 | if s == "" { |
| 26 | return def, nil |
| 27 | } |
| 28 | n, err := strconv.Atoi(s) |
| 29 | if err != nil { |
| 30 | var v apperr.ValidationError |
| 31 | v.Add(key, "must be a whole number") |
| 32 | return 0, v.Err() |
| 33 | } |
| 34 | return n, nil |
| 35 | } |