Go - Topic.Publish()

Publish an event (push based message) to a topic.

import (
  "context"
  "fmt"

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

func main() {
  updates, err := nitric.NewTopic("updates").Allow(nitric.TopicPublishing)
  if err != nil {
    fmt.Println(err)

    return
  }

  updates.Publish(context.TODO(),
    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
    map[string]interface{}
    Description

    The event to publish to the topic.

  • 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").Allow(nitric.TopicPublishing)
  if err != nil {
    fmt.Println(err)

    return
  }

  err := updates.Publish(context.TODO(),
    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").Allow(nitric.TopicPublishing)
  if err != nil {
    fmt.Println(err)

    return
  }

  updates.Publish(context.TODO(), map[string]interface{}{
      "something": "amazing happened",
    }, events.WithDelay(time.Hour))

  if err := nitric.Run(); err != nil {
    fmt.Println(err)
  }
}