2019-11-02 13:25:10 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
2020-04-23 17:14:30 +01:00
|
|
|
"fmt"
|
2019-11-02 13:25:10 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Errors ...
|
|
|
|
var (
|
2019-11-15 13:41:40 +00:00
|
|
|
ErrNotFound = errors.New("kubernetes: resource not found")
|
2019-11-02 13:25:10 +00:00
|
|
|
ErrDecode = errors.New("kubernetes: error decoding")
|
2019-11-15 13:41:40 +00:00
|
|
|
ErrUnknown = errors.New("kubernetes: unknown error")
|
2019-11-02 13:25:10 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Status is an object that is returned when a request
|
|
|
|
// failed or delete succeeded.
|
2020-01-18 02:28:44 +00:00
|
|
|
type Status struct {
|
|
|
|
Kind string `json:"kind"`
|
|
|
|
Status string `json:"status"`
|
|
|
|
Message string `json:"message"`
|
|
|
|
Reason string `json:"reason"`
|
|
|
|
Code int `json:"code"`
|
|
|
|
}
|
2019-11-02 13:25:10 +00:00
|
|
|
|
|
|
|
// Response ...
|
|
|
|
type Response struct {
|
|
|
|
res *http.Response
|
|
|
|
err error
|
|
|
|
|
|
|
|
body []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error returns an error
|
|
|
|
func (r *Response) Error() error {
|
|
|
|
return r.err
|
|
|
|
}
|
|
|
|
|
|
|
|
// StatusCode returns status code for response
|
|
|
|
func (r *Response) StatusCode() int {
|
|
|
|
return r.res.StatusCode
|
|
|
|
}
|
|
|
|
|
|
|
|
// Into decode body into `data`
|
|
|
|
func (r *Response) Into(data interface{}) error {
|
|
|
|
if r.err != nil {
|
|
|
|
return r.err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer r.res.Body.Close()
|
|
|
|
decoder := json.NewDecoder(r.res.Body)
|
2020-04-23 17:14:30 +01:00
|
|
|
if err := decoder.Decode(&data); err != nil {
|
|
|
|
return fmt.Errorf("%v: %v", ErrDecode, err)
|
2019-11-02 13:25:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return r.err
|
|
|
|
}
|
|
|
|
|
2019-12-27 20:08:46 +00:00
|
|
|
func (r *Response) Close() error {
|
|
|
|
return r.res.Body.Close()
|
|
|
|
}
|
|
|
|
|
2019-11-02 13:25:10 +00:00
|
|
|
func newResponse(res *http.Response, err error) *Response {
|
|
|
|
r := &Response{
|
|
|
|
res: res,
|
|
|
|
err: err,
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
if r.res.StatusCode == http.StatusOK ||
|
|
|
|
r.res.StatusCode == http.StatusCreated ||
|
|
|
|
r.res.StatusCode == http.StatusNoContent {
|
|
|
|
// Non error status code
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
if r.res.StatusCode == http.StatusNotFound {
|
|
|
|
r.err = ErrNotFound
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
b, err := ioutil.ReadAll(r.res.Body)
|
|
|
|
if err == nil {
|
2019-12-24 17:42:22 +00:00
|
|
|
r.err = errors.New(string(b))
|
|
|
|
return r
|
2019-11-02 13:25:10 +00:00
|
|
|
}
|
2019-12-24 17:42:22 +00:00
|
|
|
|
2019-11-15 13:41:40 +00:00
|
|
|
r.err = ErrUnknown
|
|
|
|
|
2019-11-02 13:25:10 +00:00
|
|
|
return r
|
|
|
|
}
|