Created
July 30, 2018 12:08
-
-
Save yougg/db771f28334bb0a333f4fdbd210052c4 to your computer and use it in GitHub Desktop.
simple sftp get/put api in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sftp | |
import ( | |
"errors" | |
"fmt" | |
"io" | |
"os" | |
"path/filepath" | |
"strings" | |
"time" | |
"github.com/pkg/sftp" | |
"golang.org/x/crypto/ssh" | |
) | |
type sftpClient struct { | |
host, user, password string | |
port int | |
*sftp.Client | |
} | |
// Create a new SFTP connection by given parameters | |
func NewConn(host, user, password string, port int) (client *sftpClient, err error) { | |
switch { | |
case `` == strings.TrimSpace(host), | |
`` == strings.TrimSpace(user), | |
`` == strings.TrimSpace(password), | |
0 >= port || port > 65535: | |
return nil, errors.New("Invalid parameters") | |
} | |
client = &sftpClient{ | |
host: host, | |
user: user, | |
password: password, | |
port: port, | |
} | |
if err = client.connect(); nil != err { | |
return nil, err | |
} | |
return client, nil | |
} | |
func (sc *sftpClient) connect() (err error) { | |
config := &ssh.ClientConfig{ | |
User: sc.user, | |
Auth: []ssh.AuthMethod{ssh.Password(sc.password)}, | |
Timeout: 30 * time.Second, | |
} | |
// connet to ssh | |
addr := fmt.Sprintf("%s:%d", sc.host, sc.port) | |
conn, err := ssh.Dial("tcp", addr, config) | |
if err != nil { | |
return err | |
} | |
// create sftp client | |
client, err := sftp.NewClient(conn) | |
if err != nil { | |
return err | |
} | |
sc.Client = client | |
return nil | |
} | |
// Upload file to sftp server | |
func (sc *sftpClient) Put(localFile, remoteFile string) (err error) { | |
srcFile, err := os.Open(localFile) | |
if err != nil { | |
return | |
} | |
defer srcFile.Close() | |
// Make remote directories recursion | |
parent := filepath.Dir(remoteFile) | |
path := string(filepath.Separator) | |
dirs := strings.Split(parent, path) | |
for _, dir := range dirs { | |
path = filepath.Join(path, dir) | |
sc.Mkdir(path) | |
} | |
dstFile, err := sc.Create(remoteFile) | |
if err != nil { | |
return | |
} | |
defer dstFile.Close() | |
_, err = io.Copy(dstFile, srcFile) | |
return | |
} | |
// Download file from sftp server | |
func (sc *sftpClient) Get(remoteFile, localFile string) (err error) { | |
srcFile, err := sc.Open(remoteFile) | |
if err != nil { | |
return | |
} | |
defer srcFile.Close() | |
dstFile, err := os.Create(localFile) | |
if err != nil { | |
return | |
} | |
defer dstFile.Close() | |
_, err = io.Copy(dstFile, srcFile) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment