The Go SDK is currently in experimental status. If you would like to provide feedback, please reach out to us with your suggestions and comments on our Discord.
Go - Topic.Subscribe()
Subscribe a handler to a topic and receive new events for processing.
import (
"fmt"
"github.com/nitrictech/go-sdk/handler"
"github.com/nitrictech/go-sdk/nitric"
)
func main() {
nitric.NewTopic("updates").Subscribe(func(ctx *handler.MessageContext, _ handler.MessageHandler) (*handler.MessageContext, error) {
fmt.Println("received update")
return ctx, nil
})
if err := nitric.Run(); err != nil {
fmt.Println(err)
}
}
Parameters
- Name
middleware
- Required
- Required
- Type
- EventMiddleware
- Description
The middleware (code) to be triggered by the topic.
Examples
Subscribe to a topic
import (
"fmt"
"github.com/nitrictech/go-sdk/handler"
"github.com/nitrictech/go-sdk/nitric"
)
func main() {
nitric.NewTopic("updates").Subscribe(func(ctx *handler.MessageContext, _ handler.MessageHandler) (*handler.MessageContext, error) {
fmt.Println("received update")
return ctx, nil
})
if err := nitric.Run(); err != nil {
fmt.Println(err)
}
}
Subscribe to a topic with multiple middleware
import (
"fmt"
"github.com/nitrictech/go-sdk/handler"
"github.com/nitrictech/go-sdk/nitric"
)
func validateUpdate(ctx *handler.MessageContext, next handler.MessageHandler) (*handler.MessageContext, error) {
// validate update
return next(ctx)
}
func handleUpdate(ctx *handler.MessageContext, next handler.MessageHandler) (*handler.MessageContext, error) {
// handle update
return next(ctx)
}
func main() {
nitric.NewTopic("updates").Subscribe(handler.ComposeMessageMiddleware(validateUpdate, handleUpdate))
if err := nitric.Run(); err != nil {
fmt.Println(err)
}
}
Notes
- A function may only subscribe to a topic once, if multiple subscribers are required, create them in different functions.
- A function may subscribe to OR publish to a topic but not both