Skip to content

Commit

Permalink
Remove unnecessary panics
Browse files Browse the repository at this point in the history
  • Loading branch information
dshemin committed Nov 9, 2020
1 parent 3176130 commit 999970d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 13 deletions.
12 changes: 6 additions & 6 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,17 @@ func Password(pass string) Auth {
}

// Key returns auth method from private key with or without passphrase.
func Key(prvFile string, passphrase string) Auth {
func Key(prvFile string, passphrase string) (Auth, error) {

signer, err := GetSigner(prvFile, passphrase)

if err != nil {
panic(err)
return nil, err
}

return Auth{
ssh.PublicKeys(signer),
}
}, nil
}

// HasAgent checks if ssh agent exists.
Expand All @@ -43,14 +43,14 @@ func HasAgent() bool {
}

// UseAgent auth via ssh agent, (Unix systems only)
func UseAgent() Auth {
func UseAgent() (Auth, error) {
sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
panic(fmt.Errorf("could not find ssh agent: %w", err))
return nil, fmt.Errorf("could not find ssh agent: %w", err)
}
return Auth{
ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers),
}
}, nil
}

// GetSigner returns ssh signer from private key file.
Expand Down
20 changes: 15 additions & 5 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,12 @@ func (c Client) Upload(localPath string, remotePath string) (err error) {

defer local.Close()

remote, err := c.ftp().Create(remotePath)
ftp, err := c.ftp()
if err != nil {
return
}

remote, err := ftp.Create(remotePath)

if err != nil {
return
Expand All @@ -175,7 +180,12 @@ func (c Client) Download(remotePath string, localPath string) (err error) {

defer local.Close()

remote, err := c.ftp().Open(remotePath)
ftp, err := c.ftp()
if err != nil {
return
}

remote, err := ftp.Open(remotePath)

if err != nil {
return
Expand All @@ -191,15 +201,15 @@ func (c Client) Download(remotePath string, localPath string) (err error) {
}

// get sftp client if not set.
func (c *Client) ftp() *sftp.Client {
func (c *Client) ftp() (*sftp.Client, error) {

if c.sftp == nil {
sftp, err := c.NewSftp()
if err != nil {
panic(err)
return nil, err
}
c.sftp = sftp
}

return c.sftp
return c.sftp, nil
}
10 changes: 8 additions & 2 deletions examples/goph/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,23 @@ func main() {

flag.Parse()

var err error

if agent || goph.HasAgent() {

auth = goph.UseAgent()
auth, err = goph.UseAgent()

} else if pass {

auth = goph.Password(askPass("Enter SSH Password: "))

} else {

auth = goph.Key(key, getPassphrase(passphrase))
auth, err = goph.Key(key, getPassphrase(passphrase))
}

if err != nil {
panic(err)
}

client, err = goph.NewConn(&goph.Config{
Expand Down

0 comments on commit 999970d

Please sign in to comment.