hnakamur / go-scp

[Unmaintained] A scp client library written in Go
MIT License
41 stars 23 forks source link

Support writing to remote files via `io.Writer` #30

Open dominik-lekse opened 2 years ago

dominik-lekse commented 2 years ago

Provide a function which allows to files from the remote server and read from them via an io.Reader.

This is the counterpart to #27.

Description

The proposed function SendOpen returns an io.WriteCloser which allows to caller to write data to the file on the remote server.

Like argued in #27, the main advantage is that this allows the caller more controler over the writing process.

Proposed changes

Add the function SendOpen:

// SendOpen opens an io.WriteCloser to a file on the remote server.
// SendOpen will write a known number of bytes according to fileInfo to the remote file.
// The caller of SendOpen is responsible to close the returned io.WriteCloser.
// Metadata such as modified time and mode/permission of the remote will is applied from fileInfo.
func (s *SCP) SendOpen(fileInfo *FileInfo, destFile string) (io.WriteCloser, error)

Example usage

// Some data to be written
data := []byte("Hello remote file")

// Create file on remote server
fileInfo := scp.NewFileInfo("newFile.txt", len(data), 0o644, time.Now(), time.Now())
remoteWriter, err := scp.NewSCP(c).SendOpen(fileInfo, "/path/to/newFile.txt")
defer remoteWriter.Close()
if err != nil {
    panic(err)
}

// Write data to remote file
_, err = remoteWriter.Write(data)
if err != nil {
    panic(err)
}