-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathembedded_nats.go
81 lines (69 loc) · 2.28 KB
/
embedded_nats.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// enats package provides embedded NATS server that starts in a goroutine on localhost.
// Useful for testing inter-service communication.
//
// Copyright 2020 KaaIoT Technologies, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enats
import (
"fmt"
"log"
"time"
gnatsd "github.com/nats-io/gnatsd/server"
"github.com/nats-io/nats.go"
"github.com/phayes/freeport"
)
// EmbeddedNATS combines an embedded NATS server and NATS client connected to it that can be used for testing
// inter-service communication.
type EmbeddedNATS struct {
server *gnatsd.Server
Port int
Conn *nats.Conn
}
// NewEmbeddedNATS creates a new embedded NATS server bound to a randomly chosen free localhost port.
// One of the return parameters is always nil.
func NewEmbeddedNATS() (*EmbeddedNATS, error) {
port, err := freeport.GetFreePort()
if err != nil {
return nil, err
}
return &EmbeddedNATS{
server: gnatsd.New(&gnatsd.Options{Host: "localhost", Port: port}),
Port: port,
}, nil
}
// Start the embedded NATS server in a separate goroutine and connect the Conn to it.
func (n *EmbeddedNATS) Start() error {
// Start NATS server
go func() {
if err := gnatsd.Run(n.server); err != nil {
log.Printf("Error running embedded NATS server: %v", err)
}
}()
// Wait until the server is ready to accept connections
if !n.server.ReadyForConnections(time.Minute) {
return fmt.Errorf("NATS server not ready")
}
// Start NATS connector
conn, err := nats.Connect(fmt.Sprintf("nats://localhost:%d", n.Port))
if err != nil {
return fmt.Errorf("error connecting to NATS server at localhost port %d: %v", n.Port, err)
}
n.Conn = conn
return nil
}
// Stop disconnects the NATS client and shuts down the embedded NATS server.
func (n *EmbeddedNATS) Stop() {
n.Conn.Close()
n.server.Shutdown()
}