A webmail client. Forked from https://git.sr.ht/~migadu/alps
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

65 rivejä
1.1 KiB

  1. package koushin
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "errors"
  6. imapclient "github.com/emersion/go-imap/client"
  7. )
  8. func generateToken() (string, error) {
  9. b := make([]byte, 32)
  10. _, err := rand.Read(b)
  11. if err != nil {
  12. return "", err
  13. }
  14. return base64.URLEncoding.EncodeToString(b), nil
  15. }
  16. var ErrSessionExpired = errors.New("session expired")
  17. // TODO: expiration timer
  18. type ConnPool struct {
  19. // TODO: add synchronization
  20. conns map[string]*imapclient.Client
  21. }
  22. func NewConnPool() *ConnPool {
  23. return &ConnPool{
  24. conns: make(map[string]*imapclient.Client),
  25. }
  26. }
  27. func (pool *ConnPool) Get(token string) (*imapclient.Client, error) {
  28. conn, ok := pool.conns[token]
  29. if !ok {
  30. return nil, ErrSessionExpired
  31. }
  32. return conn, nil
  33. }
  34. func (pool *ConnPool) Put(conn *imapclient.Client) (token string, err error) {
  35. for {
  36. var err error
  37. token, err = generateToken()
  38. if err != nil {
  39. conn.Logout()
  40. return "", err
  41. }
  42. if _, ok := pool.conns[token]; !ok {
  43. break
  44. }
  45. }
  46. pool.conns[token] = conn
  47. go func() {
  48. <-conn.LoggedOut()
  49. delete(pool.conns, token)
  50. }()
  51. return token, nil
  52. }