github.com/abemedia/appcast@v0.4.0/target/file/file.go (about)

     1  package file
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"net/url"
     7  	"os"
     8  	"path/filepath"
     9  
    10  	"github.com/abemedia/appcast/target"
    11  )
    12  
    13  type Config struct {
    14  	Path string
    15  	URL  string
    16  }
    17  
    18  type fileTarget struct {
    19  	path string
    20  	url  string
    21  }
    22  
    23  func New(c Config) (target.Target, error) {
    24  	path, err := filepath.Abs(c.Path)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	if err = os.MkdirAll(path, 0o755); err != nil {
    29  		return nil, err
    30  	}
    31  	if c.URL == "" {
    32  		c.URL, _ = url.JoinPath("file:///", filepath.ToSlash(path))
    33  	}
    34  	return &fileTarget{path, c.URL}, nil
    35  }
    36  
    37  func (t *fileTarget) NewWriter(_ context.Context, filename string) (io.WriteCloser, error) {
    38  	path := filepath.Join(t.path, filename)
    39  	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
    40  		return nil, err
    41  	}
    42  	return os.Create(path)
    43  }
    44  
    45  func (t *fileTarget) NewReader(_ context.Context, filename string) (io.ReadCloser, error) {
    46  	return os.Open(filepath.Join(t.path, filename))
    47  }
    48  
    49  func (t *fileTarget) Remove(_ context.Context, filename string) error {
    50  	return os.Remove(filepath.Join(t.path, filename))
    51  }
    52  
    53  func (t *fileTarget) Sub(dir string) target.Target {
    54  	u, _ := url.JoinPath(t.url, dir)
    55  	return &fileTarget{path: filepath.Join(t.path, dir), url: u}
    56  }
    57  
    58  func (t *fileTarget) URL(_ context.Context, filename string) (string, error) {
    59  	return url.JoinPath(t.url, filename)
    60  }