package helper import ( "encoding/json" "io/ioutil" "net/http" "strings" "gitbase.de/apairon/mark2web/pkg/logger" ) // JSONWebRequest will GET a json object/array from a given URL func JSONWebRequest(url string) interface{} { logger.Log.Noticef("requesting url via GET %s", url) resp, err := http.Get(url) if err != nil { logger.Log.Panicf("could not get url '%s': %s", url, err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { logger.Log.Panicf("could not read body from url '%s': %s", url, err) } logger.Log.Debugf("output from url '%s':\n%s", url, string(body)) if resp.StatusCode >= 400 { logger.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 { logger.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 } logger.Log.Panicf("could not read json from '%s': invalid type", url) return nil }