github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/cli/utils.go (about) 1 package cli 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "net/http" 8 "os" 9 "strings" 10 ) 11 12 func apiHost() string { 13 return fmt.Sprintf("%s:%d", provideWebHost(), provideWebPort()) 14 } 15 16 func apiURL(path string) string { 17 path = strings.TrimLeft(path, "/") 18 return fmt.Sprintf("http://%s:%d/api/%s", provideWebHost(), provideWebPort(), path) 19 } 20 21 func apiGet(path string) (body io.ReadCloser) { 22 url := apiURL(path) 23 res, err := http.Get(url) 24 if err != nil { 25 cmdFail(fmt.Errorf("Could not connect to Tilt at %s: %v", url, err)) 26 } 27 28 if res.StatusCode != http.StatusOK { 29 failWithNonOKResponse(url, res) 30 } 31 return res.Body 32 } 33 34 func apiPostJson(path string, payload []byte) (body io.ReadCloser, status int) { 35 url := apiURL(path) 36 res, err := http.Post(url, "application/json", bytes.NewBuffer(payload)) 37 if err != nil { 38 cmdFail(fmt.Errorf("Could not connect to Tilt at %s: %v", url, err)) 39 } 40 41 return res.Body, res.StatusCode 42 } 43 44 func cmdFail(err error) { 45 _, _ = fmt.Fprintf(os.Stderr, "%v\n", err) 46 os.Exit(1) 47 } 48 49 func failWithNonOKResponse(url string, res *http.Response) { 50 body := "<no response body>" 51 b, err := io.ReadAll(res.Body) 52 if err != nil { 53 cmdFail(fmt.Errorf("Error reading response body from %s: %v", url, err)) 54 } 55 if string(b) != "" { 56 body = string(b) 57 } 58 _ = res.Body.Close() 59 cmdFail(fmt.Errorf("Request to %s failed with status %q: %s", url, res.Status, body)) 60 }