Extract IMAP functions into separate file

This commit is contained in:
Simon Ser 2019-12-02 17:58:19 +01:00
parent 594bb2ec19
commit e9d31b0940
No known key found for this signature in database
GPG key ID: 0FDE7BE0E88F5E48
2 changed files with 51 additions and 37 deletions

49
imap.go Normal file
View file

@ -0,0 +1,49 @@
package koushin
import (
"github.com/emersion/go-imap"
imapclient "github.com/emersion/go-imap/client"
)
func (s *Server) connectIMAP() (*imapclient.Client, error) {
var c *imapclient.Client
var err error
if s.imap.tls {
c, err = imapclient.DialTLS(s.imap.host, nil)
if err != nil {
return nil, err
}
} else {
c, err = imapclient.Dial(s.imap.host)
if err != nil {
return nil, err
}
if !s.imap.insecure {
if err := c.StartTLS(nil); err != nil {
c.Close()
return nil, err
}
}
}
return c, err
}
func listMailboxes(conn *imapclient.Client) ([]*imap.MailboxInfo, error) {
ch := make(chan *imap.MailboxInfo, 10)
done := make(chan error, 1)
go func () {
done <- conn.List("", "*", ch)
}()
var mailboxes []*imap.MailboxInfo
for mbox := range ch {
mailboxes = append(mailboxes, mbox)
}
if err := <-done; err != nil {
return nil, err
}
return mailboxes, nil
}

View file

@ -7,7 +7,6 @@ import (
"time" "time"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/emersion/go-imap"
imapclient "github.com/emersion/go-imap/client" imapclient "github.com/emersion/go-imap/client"
) )
@ -47,30 +46,6 @@ func NewServer(imapURL string) (*Server, error) {
return s, nil return s, nil
} }
func (s *Server) connectIMAP() (*imapclient.Client, error) {
var c *imapclient.Client
var err error
if s.imap.tls {
c, err = imapclient.DialTLS(s.imap.host, nil)
if err != nil {
return nil, err
}
} else {
c, err = imapclient.Dial(s.imap.host)
if err != nil {
return nil, err
}
if !s.imap.insecure {
if err := c.StartTLS(nil); err != nil {
c.Close()
return nil, err
}
}
}
return c, err
}
type context struct { type context struct {
echo.Context echo.Context
server *Server server *Server
@ -163,18 +138,8 @@ func New(imapURL string) *echo.Echo {
e.GET("/", func(ectx echo.Context) error { e.GET("/", func(ectx echo.Context) error {
ctx := ectx.(*context) ctx := ectx.(*context)
ch := make(chan *imap.MailboxInfo, 10) mailboxes, err := listMailboxes(ctx.conn)
done := make(chan error, 1) if err != nil {
go func () {
done <- ctx.conn.List("", "*", ch)
}()
var mailboxes []*imap.MailboxInfo
for mbox := range ch {
mailboxes = append(mailboxes, mbox)
}
if err := <-done; err != nil {
return err return err
} }