~bigbes/core-go

ref: bdd0eb3d51f24694776606484787c9a764b67016 core-go/email/worker.go -rw-r--r-- 1.8 KiB
bdd0eb3d — Thorben Günther Print IP with "invalid source IP" authError 5 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package email

import (
	"context"
	"errors"
	"log"
	"net/http"
	"strings"

	"git.sr.ht/~sircmpwn/dowork"
	gomail "gopkg.in/mail.v2"
)

var emailCtxKey = &contextKey{"email"}

type contextKey struct {
	name string
}

// Returns a task which will send this email for the work queue. If the caller
// does not need to customize the task parameters, the Enqueue function may be
// more desirable.
func NewTask(m *gomail.Message) *work.Task {
	return work.NewTask(func(ctx context.Context) error {
		return Send(ctx, m)
	}).Retries(10).After(func(ctx context.Context, task *work.Task) {
		if task.Result() == nil {
			log.Printf("Mail to %s: '%s' sent after %d attempts",
				strings.Join(m.GetHeader("To"), ";"),
				strings.Join(m.GetHeader("Subject"), ";"),
				task.Attempts())
		} else {
			log.Printf("Mail to %s: '%s' failed after %d attempts: %v",
				strings.Join(m.GetHeader("To"), ";"),
				strings.Join(m.GetHeader("Subject"), ";"),
				task.Attempts(), task.Result())
		}
	})
}

// Enqueues an email for sending with the default parameters.
func Enqueue(ctx context.Context, m *gomail.Message) {
	ForContext(ctx).Enqueue(NewTask(m))
}

// Creates a new email processing queue.
func NewQueue() *work.Queue {
	return work.NewQueue("email")
}

// Returns the email worker for this context.
func ForContext(ctx context.Context) *work.Queue {
	q, ok := ctx.Value(emailCtxKey).(*work.Queue)
	if !ok {
		panic(errors.New("No email worker for this context"))
	}
	return q
}

// Adds HTTP middleware to provide an email work queue to this context.
func Middleware(worker *work.Queue) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx := context.WithValue(r.Context(), emailCtxKey, worker)
			r = r.WithContext(ctx)
			next.ServeHTTP(w, r)
		})
	}
}