or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid@v1.0.0
tile.json

tessl/golang-github-com-azure-azure-sdk-for-go-sdk-messaging-eventgrid-azeventgrid

tessl install tessl/golang-github-com-azure-azure-sdk-for-go-sdk-messaging-eventgrid-azeventgrid@1.0.0

Azure Event Grid client library for publishing events to Event Grid topics using EventGrid schema, CloudEvent schema, or custom formats with support for multiple authentication methods.

index.mddocs/

Azure Event Grid Client for Go

The azeventgrid package provides a Go client library for publishing events to Azure Event Grid topics. It supports three event schemas (EventGrid, CloudEvent, and custom formats) and offers flexible authentication methods including Azure Active Directory token credentials, shared key credentials, and Shared Access Signature (SAS) tokens.

Package Information

  • Package Name: azeventgrid
  • Package Type: golang
  • Language: Go
  • Installation: go get github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid
  • Import Path: github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid
  • Minimum Go Version: 1.18

Core Imports

import (
    "context"
    "time"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/azcore/messaging"
    "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

Basic Usage

Publishing EventGrid Schema Events

package main

import (
    "context"
    "log"
    "time"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

func main() {
    // Event Grid topic endpoint URL
    endpoint := "https://<topic-name>.<region>.eventgrid.azure.net/api/events"

    // Authenticate using a shared key
    key := "<your-access-key>"
    client, err := azeventgrid.NewClientWithSharedKeyCredential(
        endpoint,
        azcore.NewKeyCredential(key),
        nil,
    )
    if err != nil {
        log.Fatalf("failed to create client: %v", err)
    }

    // Create EventGrid schema events
    events := []azeventgrid.Event{
        {
            Data:        map[string]string{"message": "Hello Event Grid"},
            DataVersion: to.Ptr("1.0"),
            EventType:   to.Ptr("Custom.Event.Type"),
            EventTime:   to.Ptr(time.Now()),
            ID:          to.Ptr("unique-event-id-123"),
            Subject:     to.Ptr("example/subject"),
        },
    }

    // Publish the events
    _, err = client.PublishEvents(context.Background(), events, nil)
    if err != nil {
        log.Fatalf("failed to publish events: %v", err)
    }

    log.Println("Events published successfully")
}

Publishing CloudEvents

package main

import (
    "context"
    "log"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/azcore/messaging"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

func main() {
    endpoint := "https://<topic-name>.<region>.eventgrid.azure.net/api/events"
    key := "<your-access-key>"

    client, err := azeventgrid.NewClientWithSharedKeyCredential(
        endpoint,
        azcore.NewKeyCredential(key),
        nil,
    )
    if err != nil {
        log.Fatalf("failed to create client: %v", err)
    }

    // Create CloudEvent
    cloudEvent, err := messaging.NewCloudEvent(
        "source/application",
        "eventtype",
        map[string]interface{}{"key": "value"},
        nil,
    )
    if err != nil {
        log.Fatalf("failed to create cloud event: %v", err)
    }

    events := []messaging.CloudEvent{cloudEvent}

    // Publish CloudEvents
    _, err = client.PublishCloudEvents(context.Background(), events, nil)
    if err != nil {
        log.Fatalf("failed to publish cloud events: %v", err)
    }

    log.Println("CloudEvents published successfully")
}

Capabilities

Client Creation with Token Credential

Creates a client that authenticates using Azure Active Directory token credentials.

func NewClient(
    endpoint string,
    tokenCredential azcore.TokenCredential,
    options *ClientOptions,
) (*Client, error)

Parameters:

  • endpoint (string): The Event Grid topic endpoint URL (format: https://<topic-name>.<region>.eventgrid.azure.net/api/events)
  • tokenCredential (azcore.TokenCredential): Azure AD token credential from the azidentity package (e.g., DefaultAzureCredential, ClientSecretCredential)
  • options (*ClientOptions): Optional client configuration settings. Pass nil for defaults.

Returns:

  • *Client: Configured Event Grid client
  • error: Error if client creation fails

Usage Example:

import (
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
    // handle error
}

client, err := azeventgrid.NewClient(
    "https://mytopic.westus2.eventgrid.azure.net/api/events",
    cred,
    nil,
)
if err != nil {
    // handle error
}

Client Creation with Shared Key Credential

Creates a client that authenticates using a shared access key.

func NewClientWithSharedKeyCredential(
    endpoint string,
    keyCred *azcore.KeyCredential,
    options *ClientOptions,
) (*Client, error)

Parameters:

  • endpoint (string): The Event Grid topic endpoint URL
  • keyCred (*azcore.KeyCredential): Shared key credential created with azcore.NewKeyCredential(key)
  • options (*ClientOptions): Optional client configuration settings. Pass nil for defaults.

Returns:

  • *Client: Configured Event Grid client
  • error: Error if client creation fails

Usage Example:

import (
    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

client, err := azeventgrid.NewClientWithSharedKeyCredential(
    "https://mytopic.westus2.eventgrid.azure.net/api/events",
    azcore.NewKeyCredential("your-access-key"),
    nil,
)
if err != nil {
    // handle error
}

Client Creation with SAS Token

Creates a client that authenticates using a Shared Access Signature (SAS) token.

func NewClientWithSAS(
    endpoint string,
    sasCred *azcore.SASCredential,
    options *ClientOptions,
) (*Client, error)

Parameters:

  • endpoint (string): The Event Grid topic endpoint URL
  • sasCred (*azcore.SASCredential): SAS credential created with azcore.NewSASCredential(sasToken)
  • options (*ClientOptions): Optional client configuration settings. Pass nil for defaults.

Returns:

  • *Client: Configured Event Grid client
  • error: Error if client creation fails

Usage Example:

import (
    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

client, err := azeventgrid.NewClientWithSAS(
    "https://mytopic.westus2.eventgrid.azure.net/api/events",
    azcore.NewSASCredential("your-sas-token"),
    nil,
)
if err != nil {
    // handle error
}

Publishing EventGrid Schema Events

Publishes a batch of events using the Azure Event Grid schema. The topic must be configured to accept EventGrid schema events.

func (client *Client) PublishEvents(
    ctx context.Context,
    events []Event,
    options *PublishEventsOptions,
) (PublishEventsResponse, error)

Parameters:

  • ctx (context.Context): Context for request cancellation, timeout, and tracing
  • events ([]Event): Array of Event Grid schema events to publish (1 or more events)
  • options (*PublishEventsOptions): Optional parameters. Pass nil for defaults.

Returns:

  • PublishEventsResponse: Empty response struct on success
  • error: Returns *azcore.ResponseError on failure (includes HTTP status code and error details)

Usage Example:

import (
    "context"
    "time"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

events := []azeventgrid.Event{
    {
        Data:        "event data as string",
        DataVersion: to.Ptr("1.0"),
        EventType:   to.Ptr("Custom.Event.Type"),
        EventTime:   to.Ptr(time.Now()),
        ID:          to.Ptr("event-id-1"),
        Subject:     to.Ptr("subject/path"),
    },
    {
        Data:        map[string]interface{}{"key": "value"},
        DataVersion: to.Ptr("2.0"),
        EventType:   to.Ptr("Custom.Event.Type"),
        EventTime:   to.Ptr(time.Now()),
        ID:          to.Ptr("event-id-2"),
        Subject:     to.Ptr("subject/path"),
    },
}

resp, err := client.PublishEvents(context.Background(), events, nil)
if err != nil {
    // Handle error (e.g., *azcore.ResponseError)
}

Publishing CloudEvents

Publishes a batch of events using the CloudEvents 1.0 schema. The topic must be configured to accept CloudEvent schema events.

func (client *Client) PublishCloudEvents(
    ctx context.Context,
    events []messaging.CloudEvent,
    options *PublishCloudEventsOptions,
) (PublishCloudEventsResponse, error)

Parameters:

  • ctx (context.Context): Context for request cancellation, timeout, and tracing
  • events ([]messaging.CloudEvent): Array of CloudEvent schema events to publish (from github.com/Azure/azure-sdk-for-go/sdk/azcore/messaging)
  • options (*PublishCloudEventsOptions): Optional parameters including AegChannelName. Pass nil for defaults.

Returns:

  • PublishCloudEventsResponse: Empty response struct on success
  • error: Returns *azcore.ResponseError on failure

Usage Example:

import (
    "context"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore/messaging"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

cloudEvent, err := messaging.NewCloudEvent(
    "source/application",
    "eventtype",
    map[string]interface{}{"message": "data"},
    nil,
)
if err != nil {
    // handle error
}

events := []messaging.CloudEvent{cloudEvent}

resp, err := client.PublishCloudEvents(context.Background(), events, nil)
if err != nil {
    // Handle error
}

Publishing Custom Schema Events

Publishes a batch of events using a custom schema. Accepts any JSON-serializable event structure.

func (client *Client) PublishCustomEventEvents(
    ctx context.Context,
    events []any,
    options *PublishCustomEventEventsOptions,
) (PublishCustomEventEventsResponse, error)

Parameters:

  • ctx (context.Context): Context for request cancellation, timeout, and tracing
  • events ([]any): Array of custom event objects. Each event must be JSON-serializable.
  • options (*PublishCustomEventEventsOptions): Optional parameters. Pass nil for defaults.

Returns:

  • PublishCustomEventEventsResponse: Empty response struct on success
  • error: Returns *azcore.ResponseError on failure

Usage Example:

import (
    "context"

    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

type CustomEvent struct {
    ID        string `json:"id"`
    EventType string `json:"eventType"`
    Data      string `json:"data"`
}

events := []any{
    CustomEvent{
        ID:        "custom-event-1",
        EventType: "MyCustomEvent",
        Data:      "custom event data",
    },
    CustomEvent{
        ID:        "custom-event-2",
        EventType: "MyCustomEvent",
        Data:      "more custom data",
    },
}

resp, err := client.PublishCustomEventEvents(context.Background(), events, nil)
if err != nil {
    // Handle error
}

Types

Client

The main client type for interacting with Azure Event Grid.

type Client struct {
    // Contains unexported fields
}

This type should be created using one of the constructor functions (NewClient, NewClientWithSharedKeyCredential, or NewClientWithSAS) rather than direct instantiation.

Event

Represents an event in the Azure Event Grid schema format.

type Event struct {
    // REQUIRED: Event data specific to the event type.
    // Can be any JSON-serializable value (string, number, object, array, etc.)
    Data any

    // REQUIRED: The schema version of the data object (e.g., "1.0")
    DataVersion *string

    // REQUIRED: The time (in UTC) the event was generated
    EventTime *time.Time

    // REQUIRED: The type of the event that occurred (e.g., "Custom.Event.Type")
    EventType *string

    // REQUIRED: A unique identifier for the event
    ID *string

    // REQUIRED: A resource path relative to the topic path
    Subject *string

    // The resource path of the event source (optional)
    Topic *string

    // READ-ONLY: The schema version of the event metadata
    // This field is set by Event Grid and should not be modified
    MetadataVersion *string
}

Field Details:

  • Data: The payload of the event. Can be any type that is JSON-serializable (primitives, structs, maps, slices, etc.)
  • DataVersion: User-defined version string for the data schema (e.g., "1.0", "2.0")
  • EventTime: Timestamp when the event occurred, typically set to time.Now()
  • EventType: Application-defined event type identifier (e.g., "OrderPlaced", "FileUploaded")
  • ID: Unique identifier for this specific event instance
  • Subject: Resource path or identifier that the event relates to (e.g., "orders/12345")
  • Topic: Automatically populated by Event Grid with the topic resource path
  • MetadataVersion: Automatically set by Event Grid (do not populate manually)

Methods:

// MarshalJSON implements custom JSON marshaling for Event
func (e Event) MarshalJSON() ([]byte, error)

// UnmarshalJSON implements custom JSON unmarshaling for Event
func (e *Event) UnmarshalJSON(data []byte) error

ClientOptions

Configuration options for creating a Client.

type ClientOptions struct {
    // Embedded standard Azure SDK client options
    azcore.ClientOptions
}

The embedded azcore.ClientOptions provides:

  • Retry: Retry policy configuration
  • Telemetry: Telemetry settings
  • Transport: Custom HTTP transport
  • PerCallPolicies: Policies executed once per API call
  • PerRetryPolicies: Policies executed for each retry
  • Logging: Logging configuration

Pass nil for default settings.

PublishEventsOptions

Optional parameters for PublishEvents method.

type PublishEventsOptions struct {
    // Currently no optional parameters
    // This is a placeholder for future optional parameters
}

Pass nil when calling PublishEvents.

PublishCloudEventsOptions

Optional parameters for PublishCloudEvents method.

type PublishCloudEventsOptions struct {
    // Optional channel name header.
    // Required only when publishing to partner namespaces with
    // partner topic routing mode ChannelNameHeader.
    AegChannelName *string
}

Field Details:

  • AegChannelName: Specifies the channel name when publishing to partner namespaces. Only needed for advanced partner namespace scenarios with channel-based routing. Pass nil for standard Event Grid topics.

PublishCustomEventEventsOptions

Optional parameters for PublishCustomEventEvents method.

type PublishCustomEventEventsOptions struct {
    // Currently no optional parameters
    // This is a placeholder for future optional parameters
}

Pass nil when calling PublishCustomEventEvents.

PublishEventsResponse

Response returned by PublishEvents method.

type PublishEventsResponse struct {
    // Currently no response values
    // This is a placeholder for future response values
}

Success is indicated by a nil error. The response struct is currently empty.

PublishCloudEventsResponse

Response returned by PublishCloudEvents method.

type PublishCloudEventsResponse struct {
    // Currently no response values
    // This is a placeholder for future response values
}

Success is indicated by a nil error. The response struct is currently empty.

PublishCustomEventEventsResponse

Response returned by PublishCustomEventEvents method.

type PublishCustomEventEventsResponse struct {
    // Currently no response values
    // This is a placeholder for future response values
}

Success is indicated by a nil error. The response struct is currently empty.

Error Handling

All publish methods return an error that can be type-asserted to *azcore.ResponseError for detailed error information:

import (
    "errors"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
)

_, err := client.PublishEvents(ctx, events, nil)
if err != nil {
    var respErr *azcore.ResponseError
    if errors.As(err, &respErr) {
        // Access HTTP status code
        statusCode := respErr.StatusCode

        // Access error code and message
        errorCode := respErr.ErrorCode

        // Log full details
        log.Printf("Failed to publish: status=%d, code=%s, error=%v",
            statusCode, errorCode, respErr)
    } else {
        // Handle non-HTTP errors (e.g., network errors)
        log.Printf("Failed to publish: %v", err)
    }
}

Common error status codes:

  • 400 Bad Request: Invalid event format or missing required fields
  • 401 Unauthorized: Invalid or missing authentication credentials
  • 403 Forbidden: Valid credentials but insufficient permissions
  • 413 Payload Too Large: Event batch exceeds size limits (max 1 MB)
  • 500 Internal Server Error: Service-side error

Authentication

Token Credential (Azure AD)

Uses Azure Active Directory for authentication. Requires appropriate RBAC permissions on the Event Grid topic.

import (
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

// Use DefaultAzureCredential for automatic credential discovery
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
    // handle error
}

client, err := azeventgrid.NewClient(endpoint, cred, nil)

// Or use specific credential types:
// - azidentity.NewClientSecretCredential
// - azidentity.NewClientCertificateCredential
// - azidentity.NewManagedIdentityCredential

Required Azure RBAC Role: EventGrid Data Sender or EventGrid Contributor

Shared Key Credential

Uses the Event Grid topic access key for authentication.

import (
    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

// Access key can be retrieved from Azure Portal
// under Event Grid topic -> Access keys
key := "your-access-key"

client, err := azeventgrid.NewClientWithSharedKeyCredential(
    endpoint,
    azcore.NewKeyCredential(key),
    nil,
)

SAS Token

Uses a time-limited Shared Access Signature token.

import (
    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/messaging/eventgrid/azeventgrid"
)

// SAS token can be generated using Azure CLI or programmatically
sasToken := "your-sas-token"

client, err := azeventgrid.NewClientWithSAS(
    endpoint,
    azcore.NewSASCredential(sasToken),
    nil,
)

Event Schemas

EventGrid Schema

Native Azure Event Grid schema with defined structure. Use Event type and PublishEvents method.

When to use:

  • Publishing to Event Grid topics configured for EventGrid schema
  • Need Azure Event Grid's native event structure with metadata versioning
  • Want built-in Event Grid integration features

CloudEvents Schema

CNCF CloudEvents 1.0 specification format. Use messaging.CloudEvent type from azcore/messaging package and PublishCloudEvents method.

When to use:

  • Publishing to Event Grid topics configured for CloudEvent schema
  • Need interoperability with other cloud platforms and CNCF ecosystem
  • Want CloudEvents standard compliance

Creating CloudEvents:

import "github.com/Azure/azure-sdk-for-go/sdk/azcore/messaging"

// Basic CloudEvent
event, err := messaging.NewCloudEvent(
    "source",      // source URI
    "eventtype",   // event type
    data,          // event data (any JSON-serializable type)
    nil,           // options (for setting optional fields)
)

// CloudEvent with options
event, err := messaging.NewCloudEvent(
    "https://example.com/source",
    "com.example.event",
    map[string]string{"key": "value"},
    &messaging.CloudEventOptions{
        Subject:         to.Ptr("subject/path"),
        DataContentType: to.Ptr("application/json"),
    },
)

Custom Schema

User-defined event format. Use any JSON-serializable type and PublishCustomEventEvents method.

When to use:

  • Publishing to Event Grid topics configured for custom schema
  • Have existing event format that doesn't match EventGrid or CloudEvent schemas
  • Need maximum flexibility in event structure

Best Practices

Batch Publishing

Publish multiple events in a single request for better performance and reduced costs:

// Good: Batch multiple events
events := []azeventgrid.Event{event1, event2, event3}
_, err := client.PublishEvents(ctx, events, nil)

// Avoid: Publishing events individually
for _, event := range events {
    _, err := client.PublishEvents(ctx, []azeventgrid.Event{event}, nil)
    // This makes multiple network calls
}

Limits:

  • Maximum batch size: 1 MB
  • Maximum events per batch: 5000 (for EventGrid schema) or 100 (for CloudEvents)

Context Usage

Always pass appropriate context for timeout and cancellation control:

import "time"

// Set timeout for publish operation
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

_, err := client.PublishEvents(ctx, events, nil)

Event ID Generation

Use unique, stable IDs for event deduplication and tracking:

import (
    "github.com/google/uuid"
    "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)

// Generate unique ID
eventID := uuid.New().String()

event := azeventgrid.Event{
    ID: to.Ptr(eventID),
    // ... other fields
}

Pointer Fields

Use the to.Ptr helper from azcore/to package for required pointer fields:

import "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"

event := azeventgrid.Event{
    DataVersion: to.Ptr("1.0"),
    EventType:   to.Ptr("Custom.Event"),
    EventTime:   to.Ptr(time.Now()),
    ID:          to.Ptr("event-id"),
    Subject:     to.Ptr("subject"),
    Data:        eventData,
}

Client Reuse

Create the client once and reuse it for multiple publish operations:

// Good: Reuse client
client, err := azeventgrid.NewClient(endpoint, cred, nil)
if err != nil {
    // handle error
}

// Publish multiple times with same client
_, err = client.PublishEvents(ctx, events1, nil)
_, err = client.PublishEvents(ctx, events2, nil)

// Avoid: Creating new client for each publish
for _, eventBatch := range batches {
    client, _ := azeventgrid.NewClient(endpoint, cred, nil) // Don't do this
    client.PublishEvents(ctx, eventBatch, nil)
}

Logging

Enable Azure SDK logging for troubleshooting:

import (
    "fmt"
    "os"

    azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
)

// Set environment variable
os.Setenv("AZURE_SDK_GO_LOGGING", "all")

// Configure log listener
azlog.SetListener(func(event azlog.Event, message string) {
    fmt.Printf("[%s] %s\n", event, message)
})

Log events include:

  • HTTP request/response details
  • Retry attempts
  • Authentication token acquisition
  • Error details