github.com/paketo-buildpacks/packit@v1.3.2-0.20211206231111-86b75c657449/servicebindings/entry.go (about) 1 package servicebindings 2 3 import ( 4 "os" 5 ) 6 7 // Entry represents the read-only content of a binding entry. 8 type Entry struct { 9 path string 10 file *os.File 11 } 12 13 // NewEntry returns a new Entry whose content is given by the file at the provided path. 14 func NewEntry(path string) *Entry { 15 return &Entry{ 16 path: path, 17 } 18 } 19 20 // ReadBytes reads the entire raw content of the entry. There is no need to call Close after calling ReadBytes. 21 func (e *Entry) ReadBytes() ([]byte, error) { 22 return os.ReadFile(e.path) 23 } 24 25 // ReadString reads the entire content of the entry as a string. There is no need to call Close after calling 26 // ReadString. 27 func (e *Entry) ReadString() (string, error) { 28 bytes, err := e.ReadBytes() 29 if err != nil { 30 return "", err 31 } 32 return string(bytes), nil 33 } 34 35 // Read reads up to len(b) bytes from the entry. It returns the number of bytes read and any error encountered. At end 36 // of entry data, Read returns 0, io.EOF. 37 // Close must be called when all read operations are complete. 38 func (e *Entry) Read(b []byte) (int, error) { 39 if e.file == nil { 40 file, err := os.Open(e.path) 41 if err != nil { 42 return 0, err 43 } 44 e.file = file 45 } 46 return e.file.Read(b) 47 } 48 49 // Close closes the entry and resets it for reading. After calling Close, any subsequent calls to Read will read entry 50 // data from the beginning. Close may be called on a closed entry without error. 51 func (e *Entry) Close() error { 52 if e.file == nil { 53 return nil 54 } 55 defer func() { 56 e.file = nil 57 }() 58 return e.file.Close() 59 }