-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrequest.go
59 lines (45 loc) · 1.23 KB
/
request.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
56
57
58
59
package rest
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"strings"
)
// CheckPathVariables see if any pathVariables match on params, if dont, add to a slice.
// Actually this works just on mux.Vars()
// TODO: make working in standard library
func CheckPathVariables(params map[string]string, pathVariables ...string) error {
fields := make([]string, 0)
for _, pathVariable := range pathVariables {
if _, ok := params[pathVariable]; !ok {
fields = append(fields, pathVariable)
}
}
if len(fields) > 0 {
return fmt.Errorf("params %s dont exists in the context", strings.Join(fields, ", "))
}
return nil
}
// GetPathVariable
func GetPathVariable(key string, params map[string]string) string {
if param, ok := params[key]; !ok {
return ""
} else {
return param
}
}
// GetBody get the content of body on request and unmarshal a pointer to a <T> to attach on body
func GetBody(reader io.ReadCloser, result interface{}) error {
bytes, err := ioutil.ReadAll(reader)
defer reader.Close()
if err != nil {
return fmt.Errorf("couldn't read body of request: %v", err)
}
// TODO can do better performance
err = json.Unmarshal(bytes, result)
if err != nil {
return fmt.Errorf("couldn't unmarshal: %v", err)
}
return nil
}