-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
64 lines (50 loc) · 1.45 KB
/
service.go
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
package sender
import (
"context"
"strings"
manifest "github.com/estafette/estafette-ci-manifest"
"github.com/nats-io/nats.go"
"github.com/opentracing/opentracing-go"
"github.com/rs/zerolog/log"
)
type Service interface {
CreateConnection(ctx context.Context, hosts []string) (err error)
CloseConnection(ctx context.Context)
Publish(ctx context.Context, subject string, cronEvent manifest.EstafetteCronEvent) (err error)
}
func NewService() (Service, error) {
return &service{}, nil
}
type service struct {
natsConnection *nats.Conn
natsEncodedConnection *nats.EncodedConn
}
func (s *service) CreateConnection(ctx context.Context, hosts []string) (err error) {
s.natsConnection, err = nats.Connect(strings.Join(hosts, ","))
if err != nil {
return
}
s.natsEncodedConnection, err = nats.NewEncodedConn(s.natsConnection, nats.JSON_ENCODER)
if err != nil {
return
}
return nil
}
func (s *service) CloseConnection(ctx context.Context) {
if s.natsEncodedConnection != nil {
s.natsEncodedConnection.Close()
}
if s.natsConnection != nil {
s.natsConnection.Close()
}
}
func (s *service) Publish(ctx context.Context, subject string, cronEvent manifest.EstafetteCronEvent) (err error) {
log.Info().Msgf("Publishing cron event to queue with subject %v", subject)
span, _ := opentracing.StartSpanFromContext(ctx, "sender:Send")
defer span.Finish()
err = s.natsEncodedConnection.Publish(subject, &cronEvent)
if err != nil {
return
}
return
}