* feat(api/bolt): backport bolt changes * feat(api/exec): backport exec changes * feat(api/http): backport http/handler/dockerhub changes * feat(api/http): backport http/handler/endpoints changes * feat(api/http): backport http/handler/registries changes * feat(api/http): backport http/handler/stacks changes * feat(api/http): backport http/handler changes * feat(api/http): backport http/proxy/factory/azure changes * feat(api/http): backport http/proxy/factory/docker changes * feat(api/http): backport http/proxy/factory/utils changes * feat(api/http): backport http/proxy/factory/kubernetes changes * feat(api/http): backport http/proxy/factory changes * feat(api/http): backport http/security changes * feat(api/http): backport http changes * feat(api/internal): backport internal changes * feat(api): backport api changes * feat(api/kubernetes): backport kubernetes changes * fix(api/http): changes on backend following backport
82 lines
1.7 KiB
Go
82 lines
1.7 KiB
Go
package utils
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/ioutil"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// GetJSONObject will extract an object from a specific property of another JSON object.
|
|
// Returns nil if nothing is associated to the specified key.
|
|
func GetJSONObject(jsonObject map[string]interface{}, property string) map[string]interface{} {
|
|
object := jsonObject[property]
|
|
if object != nil {
|
|
return object.(map[string]interface{})
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func getBody(body io.ReadCloser, contentType string, isGzip bool) (interface{}, error) {
|
|
if body == nil {
|
|
return nil, errors.New("unable to parse response: empty response body")
|
|
}
|
|
|
|
reader := body
|
|
|
|
if isGzip {
|
|
gzipReader, err := gzip.NewReader(reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
reader = gzipReader
|
|
}
|
|
|
|
defer reader.Close()
|
|
|
|
bodyBytes, err := ioutil.ReadAll(reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = body.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var data interface{}
|
|
err = unmarshal(contentType, bodyBytes, &data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return data, nil
|
|
}
|
|
|
|
func marshal(contentType string, data interface{}) ([]byte, error) {
|
|
switch contentType {
|
|
case "application/yaml":
|
|
return yaml.Marshal(data)
|
|
case "application/json", "":
|
|
return json.Marshal(data)
|
|
}
|
|
|
|
return nil, fmt.Errorf("content type is not supported for marshaling: %s", contentType)
|
|
}
|
|
|
|
func unmarshal(contentType string, body []byte, returnBody interface{}) error {
|
|
switch contentType {
|
|
case "application/yaml":
|
|
return yaml.Unmarshal(body, returnBody)
|
|
case "application/json", "":
|
|
return json.Unmarshal(body, returnBody)
|
|
}
|
|
|
|
return fmt.Errorf("content type is not supported for unmarshaling: %s", contentType)
|
|
}
|