-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelperFunctions.go
More file actions
48 lines (42 loc) · 1.06 KB
/
helperFunctions.go
File metadata and controls
48 lines (42 loc) · 1.06 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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
// GetJSONFromURL does exactly what the name suggests. Takes in an URL, returns
// a map containing the JSON.
func GetJSONFromURL(url string) (map[string]interface{}, error) {
response, err := http.Get(url)
if err != nil {
return nil, errors.New("GET failed")
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, errors.New("Read failed")
}
var decoded map[string]interface{}
err = json.Unmarshal(body, &decoded)
if err != nil {
return nil, errors.New("JSON Unmarshal failed")
}
return decoded, nil
}
// GetKeyFromJSON takes in a map containing a JSON, and searches it for key
func GetKeyFromJSON(json map[string]interface{}, key string, recursive bool) (string, error) {
for k, v := range json {
if mv, ok := v.(map[string]interface{}); ok {
if recursive {
GetKeyFromJSON(mv, key, recursive)
}
} else {
if k == key {
return fmt.Sprintf("%v", v), nil
}
}
}
return "", errors.New("Key not found")
}