github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/cli/visitor/visitor.go (about) 1 package visitor 2 3 import ( 4 "fmt" 5 "io" 6 "net/http" 7 "os" 8 ) 9 10 // A simplified version of cli-runtime/pkg/resource Visitor 11 // for objects that don't query the cluster. 12 type Interface interface { 13 Name() string 14 Open() (io.ReadCloser, error) 15 } 16 17 func Stdin(stdin io.Reader) stdinVisitor { 18 return stdinVisitor{reader: stdin} 19 } 20 21 type noOpCloseReader struct { 22 io.Reader 23 } 24 25 func (noOpCloseReader) Close() error { return nil } 26 27 type stdinVisitor struct { 28 reader io.Reader 29 } 30 31 func (v stdinVisitor) Name() string { 32 return "stdin" 33 } 34 35 func (v stdinVisitor) Open() (io.ReadCloser, error) { 36 return noOpCloseReader{Reader: v.reader}, nil 37 } 38 39 var _ Interface = stdinVisitor{} 40 41 func File(path string) fileVisitor { 42 return fileVisitor{path: path} 43 } 44 45 type fileVisitor struct { 46 path string 47 } 48 49 func (v fileVisitor) Name() string { 50 return v.path 51 } 52 53 func (v fileVisitor) Open() (io.ReadCloser, error) { 54 return os.Open(v.path) 55 } 56 57 var _ Interface = urlVisitor{} 58 59 type HTTPClient interface { 60 Get(url string) (*http.Response, error) 61 } 62 63 func URL(client HTTPClient, url string) urlVisitor { 64 return urlVisitor{client: client, url: url} 65 } 66 67 type urlVisitor struct { 68 client HTTPClient 69 url string 70 } 71 72 func (v urlVisitor) Name() string { 73 return v.url 74 } 75 76 func (v urlVisitor) Open() (io.ReadCloser, error) { 77 resp, err := v.client.Get(v.url) 78 if err != nil { 79 return nil, err 80 } 81 if resp.StatusCode != http.StatusOK { 82 return nil, fmt.Errorf("fetch(%q) failed with status code %d", v.url, resp.StatusCode) 83 } 84 return resp.Body, nil 85 } 86 87 var _ Interface = urlVisitor{}