This commit is contained in:
52
pkg/helper/webrequest.go
Normal file
52
pkg/helper/webrequest.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package helper
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func JSONWebRequest(url string) interface{} {
|
||||
Log.Noticef("requesting url via GET %s", url)
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
Log.Panicf("could not get url '%s': %s", url, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
Log.Panicf("could not read body from url '%s': %s", url, err)
|
||||
}
|
||||
|
||||
Log.Debugf("output from url '%s':\n%s", url, string(body))
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
Log.Panicf("bad status '%d - %s' from url '%s'", resp.StatusCode, resp.Status, url)
|
||||
}
|
||||
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
|
||||
if strings.Contains(contentType, "json") {
|
||||
|
||||
} else {
|
||||
Log.Panicf("is not json '%s' from url '%s'", contentType, url)
|
||||
}
|
||||
|
||||
jsonMap := make(map[string]interface{})
|
||||
err = json.Unmarshal(body, &jsonMap)
|
||||
if err == nil {
|
||||
return jsonMap
|
||||
}
|
||||
|
||||
jsonArrayMap := make([]map[string]interface{}, 0)
|
||||
err = json.Unmarshal(body, &jsonArrayMap)
|
||||
if err == nil {
|
||||
return jsonArrayMap
|
||||
}
|
||||
|
||||
Log.Panicf("could not read json from '%s': invalid type", url)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user