mark2web/pkg/helper/webrequest.go

56 lines
1.2 KiB
Go
Raw Normal View History

2019-03-18 13:34:52 +01:00
package helper
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
2019-03-25 09:28:58 +01:00
"gitbase.de/apairon/mark2web/pkg/logger"
2019-03-18 13:34:52 +01:00
)
2019-03-19 12:46:32 +01:00
// JSONWebRequest will GET a json object/array from a given URL
2019-03-18 13:34:52 +01:00
func JSONWebRequest(url string) interface{} {
2019-03-25 09:28:58 +01:00
logger.Log.Noticef("requesting url via GET %s", url)
2019-03-18 13:34:52 +01:00
resp, err := http.Get(url)
if err != nil {
2019-03-25 09:28:58 +01:00
logger.Log.Panicf("could not get url '%s': %s", url, err)
2019-03-18 13:34:52 +01:00
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
2019-03-25 09:28:58 +01:00
logger.Log.Panicf("could not read body from url '%s': %s", url, err)
2019-03-18 13:34:52 +01:00
}
2019-03-25 09:28:58 +01:00
logger.Log.Debugf("output from url '%s':\n%s", url, string(body))
2019-03-18 13:34:52 +01:00
if resp.StatusCode >= 400 {
2019-03-25 09:28:58 +01:00
logger.Log.Panicf("bad status '%d - %s' from url '%s'", resp.StatusCode, resp.Status, url)
2019-03-18 13:34:52 +01:00
}
contentType := resp.Header.Get("Content-Type")
if strings.Contains(contentType, "json") {
} else {
2019-03-25 09:28:58 +01:00
logger.Log.Panicf("is not json '%s' from url '%s'", contentType, url)
2019-03-18 13:34:52 +01:00
}
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
}
2019-03-25 09:28:58 +01:00
logger.Log.Panicf("could not read json from '%s': invalid type", url)
2019-03-18 13:34:52 +01:00
return nil
}