github.com/puellanivis/breton@v0.2.16/lib/files/read.go (about) 1 package files 2 3 import ( 4 "context" 5 "io" 6 "io/ioutil" 7 ) 8 9 // ReadFrom reads the entire content of an io.Reader and returns the content as a byte slice. 10 // If the Reader also implements io.Closer, it will also Close it. 11 func ReadFrom(r io.Reader) ([]byte, error) { 12 b, err := ioutil.ReadAll(r) 13 14 if c, ok := r.(io.Closer); ok { 15 if err2 := c.Close(); err == nil { 16 err = err2 17 } 18 } 19 20 return b, err 21 } 22 23 // Discard throws away the entire content of an io.Reader. 24 // If the Reader also implements io.Closer, it will also Close it. 25 // 26 // This is specifically not context aware, it is intended to always run to completion. 27 func Discard(r io.Reader) error { 28 _, err := io.Copy(ioutil.Discard, r) 29 30 if c, ok := r.(io.Closer); ok { 31 if err2 := c.Close(); err == nil { 32 err = err2 33 } 34 } 35 36 return err 37 } 38 39 // Read reads the entire content of the resource at the given URL into a byte-slice. 40 func Read(ctx context.Context, url string) ([]byte, error) { 41 f, err := Open(ctx, url) 42 if err != nil { 43 return nil, err 44 } 45 46 return ReadFrom(f) 47 }