istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/http/get.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package http 16 17 import ( 18 "bytes" 19 "fmt" 20 "io" 21 "net/http" 22 "time" 23 ) 24 25 const requestTimeout = time.Second * 1 // Default timeout. 26 27 func DoHTTPGetWithTimeout(requestURL string, t time.Duration) (*bytes.Buffer, error) { 28 return request("GET", requestURL, t, nil) 29 } 30 31 func DoHTTPGet(requestURL string) (*bytes.Buffer, error) { 32 return DoHTTPGetWithTimeout(requestURL, requestTimeout) 33 } 34 35 func GET(requestURL string, t time.Duration, headers map[string]string) (*bytes.Buffer, error) { 36 return request("GET", requestURL, t, headers) 37 } 38 39 func PUT(requestURL string, t time.Duration, headers map[string]string) (*bytes.Buffer, error) { 40 return request("PUT", requestURL, t, headers) 41 } 42 43 func request(method, requestURL string, t time.Duration, headers map[string]string) (*bytes.Buffer, error) { 44 httpClient := &http.Client{ 45 Timeout: t, 46 } 47 48 req, err := http.NewRequest(method, requestURL, nil) 49 if err != nil { 50 return nil, err 51 } 52 for k, v := range headers { 53 req.Header.Set(k, v) 54 } 55 56 response, err := httpClient.Do(req) 57 if err != nil { 58 return nil, err 59 } 60 defer response.Body.Close() 61 62 if response.StatusCode != http.StatusOK { 63 return nil, fmt.Errorf("unexpected status %d", response.StatusCode) 64 } 65 66 var b bytes.Buffer 67 if _, err := io.Copy(&b, response.Body); err != nil { 68 return nil, err 69 } 70 return &b, nil 71 }