-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
61 lines (51 loc) · 1.41 KB
/
request.go
File metadata and controls
61 lines (51 loc) · 1.41 KB
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
56
57
58
59
60
61
package httpkit
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"github.com/asaskevich/govalidator"
"github.com/gorilla/schema"
)
// RequestDecoder decode request values
var RequestDecoder = schema.NewDecoder()
func init() {
RequestDecoder.IgnoreUnknownKeys(true)
}
// ScanValues 从url.Values解析数据
func ScanValues(dst interface{}, values url.Values) error {
if err := RequestDecoder.Decode(dst, values); err != nil {
return fmt.Errorf("decode values, %w", err)
}
if _, err := govalidator.ValidateStruct(dst); err != nil {
return fmt.Errorf("validate values, %w", err)
}
return nil
}
// MustScanValue deocde request values, panic when error
func MustScanValue(dst interface{}, values url.Values) {
if err := ScanValues(dst, values); err != nil {
panic(WrapError(err).
WithStatus(http.StatusBadRequest).
WithString(err.Error()))
}
}
// ScanJSON decode json and validate
func ScanJSON(dst interface{}, r io.Reader) error {
if err := json.NewDecoder(r).Decode(dst); err != nil {
return fmt.Errorf("json decode, %w", err)
}
if _, err := govalidator.ValidateStruct(dst); err != nil {
return fmt.Errorf("validate values, %w", err)
}
return nil
}
// MustScanJSON json decode request body, panic when error
func MustScanJSON(dst interface{}, r io.Reader) {
if err := ScanJSON(dst, r); err != nil {
panic(WrapError(err).
WithStatus(http.StatusBadRequest).
WithString(err.Error()))
}
}