Skip to content

Instantly share code, notes, and snippets.

@isacikgoz
Last active December 10, 2019 19:31
Show Gist options
  • Select an option

  • Save isacikgoz/c0956630607dce55e9151e78ef574581 to your computer and use it in GitHub Desktop.

Select an option

Save isacikgoz/c0956630607dce55e9151e78ef574581 to your computer and use it in GitHub Desktop.
create smtp client with timeout
package smtptest
import (
"context"
"net"
"net/smtp"
"time"
)
func NewSMTPClient(ctx context.Context, conn net.Conn) (*smtp.Client, error) {
// we might want to handle timeout at higher level context
// in that case we will simply use context.WithCancel()
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
var c *smtp.Client
ec := make(chan error)
go func() {
var err error
c, err = smtp.NewClient(conn, "localhost:25")
if err != nil {
ec <- err
return
}
cancel()
}()
select {
case <-ctx.Done():
err := ctx.Err()
if err != nil && err.Error() != "context canceled" {
return nil, err
}
case err := <-ec:
return nil, err
}
return c, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment