nats-stream is a package for working with the NATS messaging system, providing type-safe interaction with NATS using Go generics.
- Type-safe Interface: Uses Go generics to work with messages of specific types
- Simple Configuration: Easily configured through the Options structure
- JSON by Default: Automatically handles JSON serialization/deserialization
- Custom Unmarshalers: Supports custom deserialization logic
- Validation: Uses validator for configuration correctness validation
- Logging: Includes zerolog integration for convenient logging
package main
import (
"context"
nats "github.com/kriuchkov/nats-stream"
)
type Message struct {
Content string `json:"content"`
}
func main() {
// Connection setup
opts := &nats.Options[Message]{
URL: "nats://localhost:4222",
}
// Client creation
client, err := nats.New(opts)
if err != nil {
panic(err)
}
// Message publishing
msg := &Message{Content: "Hello NATS"}
err = client.Publish(context.Background(), "my.subject", msg)
if err != nil {
panic(err)
}
// Message subscription
err = client.Subscribe(context.Background(), "my.subject", func(subject string, msg *Message) error {
// Handle received message
return nil
})
if err != nil {
panic(err)
}
}This package provides a simple and type-safe way to work with NATS, eliminating the need to manually handle message serialization and deserialization, and helps avoid runtime errors related to type mismatches.