...

Source file src/github.com/Shopify/go-storage/utils.go

Documentation: github.com/Shopify/go-storage

     1  package storage
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  )
     8  
     9  func Read(ctx context.Context, fs FS, path string, options *ReaderOptions) ([]byte, error) {
    10  	var file *File
    11  	var err error
    12  
    13  	if file, err = fs.Open(ctx, path, options); err != nil {
    14  		return nil, fmt.Errorf("unable to open %s: %w", path, err)
    15  	}
    16  
    17  	var data []byte
    18  	if data, err = io.ReadAll(file); err != nil {
    19  		_ = file.Close() // Best effort at cleaning up
    20  
    21  		return nil, fmt.Errorf("unable to read %s: %w", path, err)
    22  	}
    23  
    24  	if err = file.Close(); err != nil {
    25  		return data, fmt.Errorf("unable to close %s: %w", path, err)
    26  	}
    27  
    28  	return data, nil
    29  }
    30  
    31  func Write(ctx context.Context, fs FS, path string, data []byte, options *WriterOptions) error {
    32  	var w io.WriteCloser
    33  	var err error
    34  
    35  	if w, err = fs.Create(ctx, path, options); err != nil {
    36  		return fmt.Errorf("unable to create %s: %w", path, err)
    37  	}
    38  
    39  	if _, err = w.Write(data); err != nil {
    40  		_ = w.Close() // Best effort at cleaning up
    41  
    42  		return fmt.Errorf("unable to write %s: %w", path, err)
    43  	}
    44  
    45  	if err = w.Close(); err != nil {
    46  		return fmt.Errorf("unable to close %s: %w", path, err)
    47  	}
    48  
    49  	return nil
    50  }
    51  
    52  func Exists(ctx context.Context, fs FS, path string) bool {
    53  	attrs, _ := fs.Attributes(ctx, path, nil)
    54  
    55  	return attrs != nil
    56  }
    57  

View as plain text