-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_handler.go
55 lines (43 loc) · 1.05 KB
/
base_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package webhttp
import (
"fmt"
"net/http"
"strconv"
"github.com/go-chi/chi"
)
type baseHandler struct{}
func (uh baseHandler) pathParam(r *http.Request, name string) string {
return chi.URLParam(r, name)
}
func (uh baseHandler) pathParamInt64(r *http.Request, opts ParamInt64Opts) (int64, error) {
val := uh.pathParam(r, opts.P.Name)
return opts.parse(val)
}
func (uh baseHandler) queryParam(r *http.Request, name string) string {
return r.URL.Query().Get(name)
}
type ParamOpts struct {
Optional bool
Name string
}
type ParamInt64Opts struct {
P ParamOpts
Default int64
}
func (opts ParamInt64Opts) parse(val string) (int64, error) {
if val == "" {
if opts.P.Optional {
return opts.Default, nil
}
return 0, ErrMissingRequired
}
parsed, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return 0, fmt.Errorf("%w: %v", ErrBadFormat, err)
}
return parsed, nil
}
func (uh baseHandler) queryParamInt64(r *http.Request, opts ParamInt64Opts) (int64, error) {
val := uh.queryParam(r, opts.P.Name)
return opts.parse(val)
}