Skip to content

Commit

Permalink
Feat: Added Config and MustConnect function
Browse files Browse the repository at this point in the history
* Config for NATS Connection
* MustConnect function uses Config to connect to remote servers
* internal helper functions
  • Loading branch information
t0ff1 authored Dec 12, 2024
2 parents 71530ea + 824ff7e commit de3f628
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
2 changes: 1 addition & 1 deletion bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func newNATSBridge(servers []string, log LogFunc) (*natsBridge, error) {
url := strings.Join(servers, ",")

nb.connection, err = nats.Connect(url,
nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
nats.DisconnectErrHandler(func(_ *nats.Conn, err error) {
log("Got disconnected: %v", err)
}),
nats.ReconnectHandler(func(nc *nats.Conn) {
Expand Down
45 changes: 45 additions & 0 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package vnats

import (
"fmt"
"log/slog"
"os"
"strings"

"github.com/nats-io/nats.go"
)
Expand Down Expand Up @@ -29,6 +32,14 @@ type LogFunc func(format string, a ...interface{})
// NoLogging is the default LogFunc. It logs nothing.
var NoLogging = func(_ string, _ ...interface{}) {}

// Config is a struct to hold the configuration of a NATS connection.
type Config struct {
Password string
Username string
Hosts string
Port int
}

// Connection is the main entry point for the library. It is used to create Publishers and Subscribers.
// It is also used to close the connection to the NATS server/ cluster.
type Connection struct {
Expand Down Expand Up @@ -139,3 +150,37 @@ func WithLogger(log LogFunc) Option {
c.log = log
}
}

// MustConnectToNATS to NATS Server. This function panics if the connection could not be established.
// servers: List of NATS servers in the form of "nats://<user:password>@<host>:<port>"
// logger: an optional slog.Logger instance
func MustConnectToNATS(config *Config, logger *slog.Logger) *Connection {
if logger == nil {
logger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{}))
}
natsConn, err := Connect(servers(config), WithLogger(logger.Info))
if err != nil {
panic("error while connecting to nats: " + err.Error())
}
return natsConn
}

func servers(cfg *Config) []string {
parsedServers := trimSpaceSlice(strings.Split(cfg.Hosts, ","))
servers := make([]string, 0, len(parsedServers))

for _, server := range parsedServers {
s := fmt.Sprintf("nats://%s:%s@%s:%d", cfg.Username, cfg.Password, server, cfg.Port)
servers = append(servers, s)
}

return servers
}

func trimSpaceSlice(values []string) []string {
trimmed := make([]string, len(values))
for i, value := range values {
trimmed[i] = strings.TrimSpace(value)
}
return trimmed
}
2 changes: 1 addition & 1 deletion subscriber_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ func TestSubscriberMultiple(t *testing.T) {
}

func makeHandlerSubscriber(t *testing.T, alwaysFail bool, s *subscriptionState, idx int) func(msg Msg) error {
handler := func(msg Msg) error {
handler := func(_ Msg) error {
if alwaysFail {
s.FailedMsgs++
t.Logf("Subscriber %v: Failed msg handeling, failesp: %v", idx, s.FailedMsgs)
Expand Down

0 comments on commit de3f628

Please sign in to comment.