github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/cli/cmd/organization/request.go (about) 1 /* 2 Copyright (C) 2022-2023 ApeCloud Co., Ltd 3 4 This file is part of KubeBlocks project 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 package organization 21 22 import ( 23 "bytes" 24 "encoding/json" 25 "fmt" 26 "io" 27 "net/http" 28 29 "github.com/hashicorp/go-cleanhttp" 30 "github.com/pkg/errors" 31 ) 32 33 type ErrorResponse struct { 34 Code int `json:"code"` 35 Message string `json:"message"` 36 Reason string `json:"reason"` 37 } 38 39 func NewRequest(method, path, token string, requestBody []byte) ([]byte, error) { 40 client := cleanhttp.DefaultClient() 41 req, err := http.NewRequest(method, path, bytes.NewBuffer(requestBody)) 42 if err != nil { 43 return nil, errors.Wrapf(err, "failed to create request for %s", path) 44 } 45 46 req.Header.Set("Accept", "application/json") 47 req.Header.Set("Authorization", "Bearer "+token) 48 49 resp, err := client.Do(req) 50 if err != nil { 51 return nil, errors.Wrapf(err, "failed to perform request for %s", path) 52 } 53 defer resp.Body.Close() 54 55 if resp.StatusCode >= 400 { 56 var errorResponse ErrorResponse 57 err = json.NewDecoder(resp.Body).Decode(&errorResponse) 58 if err != nil { 59 return nil, errors.Wrapf(err, "code: %d, failed to decode error response body for %s", resp.StatusCode, path) 60 } 61 return nil, fmt.Errorf("request failed with status code: %d for %s\nreason: %s %s", resp.StatusCode, path, errorResponse.Reason, errorResponse.Message) 62 } 63 64 responseBody, err := io.ReadAll(resp.Body) 65 if err != nil { 66 return nil, errors.Wrapf(err, "failed to read response body for %s", path) 67 } 68 69 return responseBody, nil 70 }