https://github.com/sl1pm4t/gongs
Go Nats Generic Streams
https://github.com/sl1pm4t/gongs
golang golang-library nats nats-streaming
Last synced: 6 months ago
JSON representation
Go Nats Generic Streams
- Host: GitHub
- URL: https://github.com/sl1pm4t/gongs
- Owner: sl1pm4t
- License: mit
- Created: 2022-12-04T21:53:36.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2023-05-01T19:06:00.000Z (over 2 years ago)
- Last Synced: 2025-04-20T04:34:22.909Z (6 months ago)
- Topics: golang, golang-library, nats, nats-streaming
- Language: Go
- Homepage:
- Size: 14.6 KB
- Stars: 8
- Watchers: 3
- Forks: 3
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# GONGS - Go Nats Generic Streams
A thin wrapper around Nats Jetstream client that uses Go Generics to provide strongly typed NATS streams.
## Example Usage
Define the Type that will be published and retrieved from the NATS stream:
```go
type ExampleMsgEventData struct {
Id string
Type string
Description string
}
type ExampleMsg struct {
eventData *ExampleMsgEventData
}
// Mandatory - Implement the `gongs.MsgEvent` interface
func (e *ExampleMsg) GetId(ctx context.Context) string {
return e.eventData.Id
}
func (e *ExampleMsg) DecodeEventData(b []byte) error {
d := &ExampleMsgEventData{}
json.Unmarshal(b, d)
e.eventData = d
return nil
}
func (e *ExampleMsg) EncodeEventData(ctx context.Context) []byte {
b, _ := json.Marshal(e.eventData)
return b
}
```
Create a Generic Stream for the above type:
```go
// create Jetstream for Stream
cfg := &nats.StreamConfig{
Name: "EXAMPLE",
Subjects: []string{"example.>"},
Storage: nats.MemoryStorage,
Retention: nats.WorkQueuePolicy,
}
js, _ := nc.JetStream()
js.AddStream(cfg)
// create Generic Stream
q := gongs.NewGenericStream[ExampleMsg](js, "example.events", cfg.Name)
```
Publish event
```go
ctx := context.Background()
// Publish an event
q.Publish(ctx, &ExampleMsg{
eventData: &ExampleMsgEventData{
Id: "abc123",
Type: "start",
Description: "An important task has started",
},
})
```
Read the last event off queue.
```go
// Read event from NATS
event, _ := q.GetLastMsg("example")
fmt.Printf("Id: %s [%s] - %s",
event.eventData.Id,
event.eventData.Type,
event.eventData.Description,
)
```