Last active
December 10, 2019 19:31
-
-
Save isacikgoz/c0956630607dce55e9151e78ef574581 to your computer and use it in GitHub Desktop.
create smtp client with timeout
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 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