Go is in development for v1. Interested in contributing or chatting with us?Get in touch!
Go - Topic.Publish()
Publish an event (push based message) to a topic.
import (
"context"
"fmt"
"github.com/nitrictech/go-sdk/api/events"
"github.com/nitrictech/go-sdk/nitric"
)
func main() {
updates, err := nitric.NewTopic("updates").With(nitric.TopicPublishing)
if err != nil {
fmt.Println(err)
return
}
updates.Publish(context.TODO(), &events.Event{
Payload: map[string]interface{}{
"something": "amazing happened",
},
})
if err := nitric.Run(); err != nil {
fmt.Println(err)
}
}
Parameters
- Name
ctx
- Required
- Required
- Type
- context
- Description
The context of the call, used for tracing.
- Name
event
- Required
- Required
- Type
- Event
- Description
The event to publish to the topic.
- Name
ID
- Optional
- Optional
- Type
- string
- Description
Unique ID to apply to the event.
- Name
Payload
- Required
- Required
- Type
- map[string]interface{}
- Description
Payload to send with the event.
- Name
PayloadType
- Optional
- Optional
- Type
- string
- Description
A hint to the type of payload supplied.
- Name
opts
- Optional
- Optional
- Type
- PublishOption
- Description
Optional function to send a message with a delay.
Examples
Publish a message
Publishing messages to a topic will push a copy of the message to each of the topic's subscribers. By default, delivery occurs without a delay.
import (
"context"
"fmt"
"github.com/nitrictech/go-sdk/api/events"
"github.com/nitrictech/go-sdk/nitric"
)
func main() {
updates, err := nitric.NewTopic("updates").With(nitric.TopicPublishing)
if err != nil {
fmt.Println(err)
return
}
err := updates.Publish(context.TODO(), &events.Event{
Payload: map[string]interface{}{
"something": "amazing happened",
},
})
if err := nitric.Run(); err != nil {
fmt.Println(err)
}
}
Delaying message delivery
You can delay the delivery of messages sent to a topic. The current maximum delay is 7 days (604800 seconds).
import (
"context"
"fmt"
"time"
"github.com/nitrictech/go-sdk/api/events"
"github.com/nitrictech/go-sdk/nitric"
)
func main() {
updates, err := nitric.NewTopic("updates").With(nitric.TopicPublishing)
if err != nil {
fmt.Println(err)
return
}
updates.Publish(context.TODO(), &events.Event{
Payload: map[string]interface{}{
"something": "amazing happened",
},
}, events.WithDelay(time.Hour))
if err := nitric.Run(); err != nil {
fmt.Println(err)
}
}
Notes
- If an id is not supplied with an event a UUID(v4) will be generated for you.
- A function may subscribe to OR publish to a topic but not both.