nats

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 24, 2025 License: MIT Imports: 6 Imported by: 0

README

nats-stream

Overview

nats-stream is a package for working with the NATS messaging system, providing type-safe interaction with NATS using Go generics.

Key Features

  • 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

Usage Example

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.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Nats

type Nats[T any] struct {
	// contains filtered or unexported fields
}

func New

func New[T any](opts *Options[T]) (*Nats[T], error)

func (*Nats[T]) Publish

func (a *Nats[T]) Publish(ctx context.Context, subject string, message *T) error

func (*Nats[T]) Subscribe

func (a *Nats[T]) Subscribe(ctx context.Context, subject string, fn func(topic string, v *T) error) error

type Options

type Options[T any] struct {
	URL         string `validate:"required"`
	Unmarshaler func(data []byte, v *T) error
	MarshalFunc func(v *T) ([]byte, error)
}

func (*Options[T]) SetDefaults

func (opts *Options[T]) SetDefaults()

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL