Go - Topic.Subscribe()

Subscribe a handler to a topic and receive new events for processing.

import (
  "fmt"

  "github.com/nitrictech/go-sdk/faas"
  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  nitric.NewTopic("updates").Subscribe(func(ctx *faas.EventContext, _ faas.EventHandler) (*faas.EventContext, 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/faas"
  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  nitric.NewTopic("updates").Subscribe(func(ctx *faas.EventContext, _ faas.EventHandler) (*faas.EventContext, 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/faas"
  "github.com/nitrictech/go-sdk/nitric"
)

func validateUpdate(ctx *faas.EventContext, next faas.EventHandler) (*faas.EventContext, error) {
  // validate update

  return next(ctx)
}

func handleUpdate(ctx *faas.EventContext, next faas.EventHandler) (*faas.EventContext, error) {
  // handle update

  return next(ctx)
}

func main() {
  nitric.NewTopic("updates").Subscribe(faas.ComposeEventMiddleware(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