forked from emersion/go-milter
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexample_server_test.go
More file actions
72 lines (62 loc) · 1.92 KB
/
example_server_test.go
File metadata and controls
72 lines (62 loc) · 1.92 KB
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
70
71
72
package milter_test
import (
"context"
"log"
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/d--j/go-milter"
)
type ExampleBackend struct {
milter.NoOpMilter
}
func (b *ExampleBackend) RcptTo(rcptTo string, esmtpArgs string, m milter.Modifier) (*milter.Response, error) {
// reject the recipient when it goes to other-spammer@example.com and is a local delivery
if rcptTo == "other-spammer@example.com" && m.Get(milter.MacroRcptMailer) == "local" {
return milter.RejectWithCodeAndReason(550, "5.7.1 We do not like you\nvery much, please go away")
}
return milter.RespContinue, nil
}
func ExampleServer() {
// create socket to listen on
socket, err := net.Listen("tcp4", "127.0.0.1:6785")
if err != nil {
log.Fatal(err)
}
defer socket.Close()
// define the backend, required actions, protocol options and macros we want
server := milter.NewServer(
milter.WithMilter(func() milter.Milter {
return &ExampleBackend{}
}),
milter.WithProtocol(milter.OptNoConnect|milter.OptNoHelo|milter.OptNoMailFrom|milter.OptNoBody|milter.OptNoHeaders|milter.OptNoEOH|milter.OptNoUnknown|milter.OptNoData),
milter.WithAction(milter.OptChangeFrom|milter.OptAddRcpt|milter.OptRemoveRcpt),
milter.WithMacroRequest(milter.StageRcpt, []milter.MacroName{milter.MacroRcptMailer}),
)
defer server.Close()
// start the milter
var wgDone sync.WaitGroup
wgDone.Add(1)
go func(socket net.Listener) {
if err := server.Serve(socket); err != nil {
log.Println(err)
}
wgDone.Done()
}(socket)
log.Printf("Started milter on %s:%s", socket.Addr().Network(), socket.Addr().String())
// wait for SIGINT or SIGTERM
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sig
log.Printf("Gracefully shutting down milter…")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
server.Shutdown(ctx)
}()
// quit when milter quits
wgDone.Wait()
}