istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pilot/pkg/request/command.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 request 16 17 import ( 18 "bytes" 19 "fmt" 20 "io" 21 "net/http" 22 "strings" 23 ) 24 25 // Command is a wrapper for making http requests to Pilot or Envoy via a CLI command. 26 type Command struct { 27 Address string 28 Client *http.Client 29 } 30 31 // Do executes an http request using the specified arguments 32 func (c *Command) Do(method, path, body string) error { 33 bodyBuffer := bytes.NewBufferString(body) 34 path = strings.TrimPrefix(path, "/") 35 url := fmt.Sprintf("http://%v/%v", c.Address, path) 36 req, err := http.NewRequest(method, url, bodyBuffer) 37 if err != nil { 38 return err 39 } 40 resp, err := c.Client.Do(req) 41 if err != nil { 42 return err 43 } 44 defer resp.Body.Close() 45 respBody, err := io.ReadAll(resp.Body) 46 if err != nil { 47 return err 48 } 49 if resp.StatusCode > 399 && resp.StatusCode != 404 { 50 return fmt.Errorf("received unsuccessful status code %v: %v", resp.StatusCode, string(respBody)) 51 } 52 fmt.Println(string(respBody)) 53 return nil 54 }