github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/runtime/kubernetes/api/response.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); 2 // you may not use this file except in compliance with the License. 3 // You may obtain a copy of the License at 4 // 5 // https://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, 9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 // See the License for the specific language governing permissions and 11 // limitations under the License. 12 // 13 // Original source: github.com/micro/go-micro/v3/util/kubernetes/api/response.go 14 15 package api 16 17 import ( 18 "encoding/json" 19 "errors" 20 "fmt" 21 "io/ioutil" 22 "net/http" 23 ) 24 25 // Errors ... 26 var ( 27 ErrNotFound = errors.New("kubernetes: resource not found") 28 ErrDecode = errors.New("kubernetes: error decoding") 29 ErrUnknown = errors.New("kubernetes: unknown error") 30 ) 31 32 // Status is an object that is returned when a request 33 // failed or delete succeeded. 34 type Status struct { 35 Kind string `json:"kind"` 36 Status string `json:"status"` 37 Message string `json:"message"` 38 Reason string `json:"reason"` 39 Code int `json:"code"` 40 } 41 42 // Response ... 43 type Response struct { 44 res *http.Response 45 err error 46 47 body []byte 48 } 49 50 // Error returns an error 51 func (r *Response) Error() error { 52 return r.err 53 } 54 55 // StatusCode returns status code for response 56 func (r *Response) StatusCode() int { 57 return r.res.StatusCode 58 } 59 60 // Into decode body into `data` 61 func (r *Response) Into(data interface{}) error { 62 if r.err != nil { 63 return r.err 64 } 65 66 defer r.res.Body.Close() 67 decoder := json.NewDecoder(r.res.Body) 68 if err := decoder.Decode(&data); err != nil { 69 return fmt.Errorf("%v: %v", ErrDecode, err) 70 } 71 72 return r.err 73 } 74 75 func (r *Response) Close() error { 76 return r.res.Body.Close() 77 } 78 79 func newResponse(res *http.Response, err error) *Response { 80 r := &Response{ 81 res: res, 82 err: err, 83 } 84 85 if err != nil { 86 return r 87 } 88 89 if r.res.StatusCode == http.StatusOK || 90 r.res.StatusCode == http.StatusCreated || 91 r.res.StatusCode == http.StatusNoContent { 92 // Non error status code 93 return r 94 } 95 96 if r.res.StatusCode == http.StatusNotFound { 97 r.err = ErrNotFound 98 return r 99 } 100 101 b, err := ioutil.ReadAll(r.res.Body) 102 if err == nil { 103 r.err = errors.New(string(b)) 104 return r 105 } 106 107 r.err = ErrUnknown 108 109 return r 110 }