### Install Go AMQP Module Source: https://github.com/azure/go-amqp/blob/main/README.md Use 'go get' to install the Azure Go AMQP module. Ensure Go 1.18 or later is installed. ```sh go get github.com/Azure/go-amqp ``` -------------------------------- ### Code Examples Source: https://github.com/azure/go-amqp/blob/main/_autodocs/README.md Collection of production-ready code examples demonstrating various usage patterns of the Go-AMQP library. ```APIDOC ## Code Examples ### Description Provides a set of production-ready code examples that illustrate common and advanced usage patterns of the Go-AMQP library. ### Example Categories - Send/Receive - Batch operations - High-throughput scenarios - Request-reply patterns - Dynamic addressing - Connection monitoring ``` -------------------------------- ### Conservative Configuration Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/MANIFEST.md Provides an example of a conservative configuration for AMQP connections, prioritizing stability and reliability. ```go conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/", amqp.ConnOptions{ IdleTimeout: time.Second * 30, WriteTimeout: time.Second * 10, MaxFrameSize: 1024 * 1024, MaxSessions: 1, Properties: map[string]interface{}{"x-service": "conservative"}, ContainerID: "conservative-container", }) session, err := conn.NewSession(nil) receiver, err := session.NewReceiver(amqp.ReceiverOptions{ Name: "conservative-receiver", SourceAddress: "my-queue", }) ``` -------------------------------- ### High-Throughput Configuration Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/MANIFEST.md Demonstrates a configuration optimized for high-throughput scenarios, focusing on performance and efficiency. ```go conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/", amqp.ConnOptions{ IdleTimeout: time.Second * 120, WriteTimeout: time.Second * 30, MaxFrameSize: 1024 * 1024 * 10, MaxSessions: 10, Properties: map[string]interface{}{"x-service": "high-throughput"}, ContainerID: "high-throughput-container", }) session, err := conn.NewSession(nil) receiver, err := session.NewReceiver(amqp.ReceiverOptions{ Name: "high-throughput-receiver", SourceAddress: "my-high-throughput-queue", Credit: 1000, }) ``` -------------------------------- ### Create AMQP Error Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Example of creating an AMQP error instance with a specific condition and description. This demonstrates how to instantiate the Error type. ```go err := &amqp.Error{ Condition: amqp.ErrCondMessageSizeExceeded, Description: "message too large", } ``` -------------------------------- ### Creating a New AMQP Sender with Options Source: https://github.com/azure/go-amqp/blob/main/_autodocs/03-sender.md Example of initializing SenderOptions and creating a new sender. Ensure necessary imports and session objects are available. ```go opts := &amqp.SenderOptions{ Name: "my-sender", Durability: amqp.DurabilityConfiguration, SettlementMode: &amqp.SenderSettleModeMixed, Properties: map[string]any{ "custom-prop": "custom-value", }, } sender, err := session.NewSender(context.TODO(), "my-queue", opts) if err != nil { return err } ``` -------------------------------- ### Durability Configuration Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Shows how to configure the Durability policy for a sender. Durability determines how the terminus state is retained. ```go opts := &amqp.SenderOptions{ Durability: amqp.DurabilityConfiguration, } ``` -------------------------------- ### Source Distribution Mode Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Demonstrates setting the SourceDistributionMode for a receiver. This affects whether messages are copied or moved from the source. ```go opts := &amqp.ReceiverOptions{ SourceDistributionMode: amqp.SourceDistributionModeCopy, } ``` -------------------------------- ### Example AMQP Message with Annotations Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Constructs an AMQP message including both standard Annotations and DeliveryAnnotations, using string keys and values. ```go msg := &amqp.Message{ Annotations: amqp.Annotations{ "x-custom-id": "abc123", "x-source": "legacy-system", }, DeliveryAnnotations: amqp.Annotations{ "x-forwarded-for": "192.168.1.100", }, Data: [][]byte{[]byte("payload")}, } ``` -------------------------------- ### Request-Reply Pattern Configuration Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/MANIFEST.md Shows a configuration tailored for implementing the request-reply pattern, ensuring efficient message exchange for synchronous operations. ```go conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/", amqp.ConnOptions{ IdleTimeout: time.Second * 60, WriteTimeout: time.Second * 15, MaxFrameSize: 1024 * 1024 * 5, MaxSessions: 5, Properties: map[string]interface{}{"x-service": "request-reply"}, ContainerID: "request-reply-container", }) session, err := conn.NewSession(nil) receiver, err := session.NewReceiver(amqp.ReceiverOptions{ Name: "request-reply-receiver", SourceAddress: "my-request-queue", }) sender, err := session.NewSender(amqp.SenderOptions{ TargetAddress: "my-reply-queue", }) ``` -------------------------------- ### Handle LinkError Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Example demonstrating how to check for and extract information from an amqp.LinkError. This pattern is useful for diagnosing link-related issues by inspecting the remote error condition. ```go _, err := receiver.Receive(context.TODO(), nil) if err != nil { if linkErr, ok := err.(*amqp.LinkError); ok { if linkErr.RemoteErr != nil { log.Printf("remote: %s", linkErr.RemoteErr.Condition) } } } ``` -------------------------------- ### Example: Creating a New Receiver Source: https://github.com/azure/go-amqp/blob/main/_autodocs/04-receiver.md Demonstrates how to create a new AMQP receiver with custom options, including name, credit, durability, filters, and properties. This is useful for setting up specific receiver configurations. ```go opts := &amqp.ReceiverOptions{ Name: "my-receiver", Credit: 10, Durability: amqp.DurabilityConfiguration, Filters: []amqp.LinkFilter{ amqp.NewSelectorFilter("custom_prop = 'value'"), }, Properties: map[string]any{ "custom": "property", }, } receiver, err := session.NewReceiver(context.TODO(), "my-queue", opts) if err != nil { return err } ``` -------------------------------- ### Configure Receiver with Selector Filter Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Example of configuring a receiver with a standard selector filter. This demonstrates how to create a filter and apply it using ReceiverOptions. ```go // Standard selector filter filter := amqp.NewSelectorFilter("priority > 5") opts := &amqp.ReceiverOptions{ Filters: []amqp.LinkFilter{filter}, } ``` -------------------------------- ### Expiry Policy and Timeout Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Illustrates setting the ExpiryPolicy and ExpiryTimeout for a receiver. This controls when the terminus expiry timer starts. ```go opts := &amqp.ReceiverOptions{ ExpiryPolicy: amqp.ExpiryPolicyConnectionClose, ExpiryTimeout: 300, // seconds } ``` -------------------------------- ### Example: Handling Receiver Errors Source: https://github.com/azure/go-amqp/blob/main/_autodocs/04-receiver.md Shows how to check for and handle `LinkError` when receiving messages. This example demonstrates type assertion to access the `RemoteErr` and log the remote error condition. ```go msg, err := receiver.Receive(context.TODO(), nil) if err != nil { if linkErr, ok := err.(*amqp.LinkError); ok && linkErr.RemoteErr != nil { log.Printf("Remote link error: %s", linkErr.RemoteErr.Condition) } return err } ``` -------------------------------- ### Sender Settle Mode Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Demonstrates setting the SenderSettleMode for a sender. This mode specifies how the sender settles messages. ```go mode := amqp.SenderSettleModeMixed opts := &amqp.SenderOptions{ SettlementMode: &mode, } ``` -------------------------------- ### Example AMQP Message with Properties Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Constructs an AMQP message with various standard properties set, including MessageID, Subject, ContentType, CreationTime, and CorrelationID. ```go subject := "order-123" msg := &amqp.Message{ Properties: &amqp.MessageProperties{ MessageID: "msg-uuid-xyz", Subject: &subject, ContentType: ptrs.String("application/json"), CreationTime: ptrs.Time(time.Now()), CorrelationID: "order-123", GroupID: ptrs.String("orders"), }, Data: [][]byte{[]byte(`{"order_id":"123"}`)}, } ``` -------------------------------- ### Example AMQP Message with Symbol ContentType Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Demonstrates setting the ContentType property of an AMQP message using the amqp.Symbol type. ```go ctType := amqp.Symbol("application/json") ``` -------------------------------- ### Receiver Settle Mode Example Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Demonstrates setting the ReceiverSettleMode for a receiver. This mode specifies how the receiver settles messages. ```go mode := amqp.ReceiverSettleModeSecond opts := &amqp.ReceiverOptions{ SettlementMode: &mode, } ``` -------------------------------- ### Receive Messages with AMQP Selectors Source: https://github.com/azure/go-amqp/blob/main/_autodocs/09-examples.md This example demonstrates how to create a receiver that filters messages based on a selector expression. Only messages matching the criteria will be received. Ensure the broker supports message selectors. ```go func selectiveReceive(ctx context.Context, session *amqp.Session) error { // Create receiver with selector filter opts := &amqp.ReceiverOptions{ Credit: 10, Filters: []amqp.LinkFilter{ amqp.NewSelectorFilter("priority > 5 AND status = 'pending'"), }, } receiver, err := session.NewReceiver(ctx, "events", opts) if err != nil { return err } defer receiver.Close(ctx) // Receive matching messages for i := 0; i < 10; i++ { msg, err := receiver.Receive(ctx, nil) if err != nil { return err } log.Printf("Received high-priority event: %s", string(msg.GetData())) if err := receiver.AcceptMessage(ctx, msg); err != nil { return err } } return nil } ``` -------------------------------- ### Go AMQP Example: Inspecting Connection Errors Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Demonstrates how to check for `*ConnError` and access the `RemoteErr` condition when a connection fails. This is useful for diagnosing specific issues reported by the AMQP server. ```go conn, err := amqp.Dial(context.TODO(), "amqps://unknown.example.com", nil) if err != nil { if connErr, ok := err.(*amqp.ConnError); ok && connErr.RemoteErr != nil { log.Printf("Remote error: %s", connErr.RemoteErr.Condition) } else { log.Printf("Connection error: %v", err) } } ``` -------------------------------- ### Access Error Info Map Source: https://github.com/azure/go-amqp/blob/main/_autodocs/07-errors.md This example demonstrates how to access and log additional broker-specific information from the `RemoteErr.Info` map, such as related addresses. ```go if remoteErr != nil && remoteErr.Info != nil { if addr, ok := remoteErr.Info["address"].(string); ok { log.Printf("address: %s", addr) } } ``` -------------------------------- ### Example AMQP Message with UUID MessageID Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Constructs an AMQP message and assigns a UUID to the MessageID property. ```go msgID := amqp.UUID{0x00, 0x11, 0x22, ...} // 16 bytes msg := &amqp.Message{ Properties: &amqp.MessageProperties{ MessageID: msgID, }, } ``` -------------------------------- ### Handle Rejected Message Source: https://github.com/azure/go-amqp/blob/main/_autodocs/07-errors.md Shows how to detect and log when a broker rejects a message, for example, due to validation failure. ```go receipt, _ := sender.SendWithReceipt(context.TODO(), msg, nil) state, err := receipt.Wait(context.TODO()) if err != nil { return err } if rejected, ok := state.(*amqp.StateRejected); ok { if rejected.Error != nil { log.Printf("rejected: %s", rejected.Error.Condition) } } ``` -------------------------------- ### Create Simple Binary AMQP Message Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Creates a new AMQP message containing only binary data and sends it using a sender. Requires context and sender setup. ```go msg := amqp.NewMessage([]byte("hello")) if err := sender.Send(context.TODO(), msg, nil); err != nil { return err } ``` -------------------------------- ### Example AMQP Message with Null Value Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Demonstrates sending a message where the primary value is explicitly null, using the amqp.Null type. ```go msg := &amqp.Message{ Value: amqp.Null{}, } ``` -------------------------------- ### Send a message and get a receipt Source: https://github.com/azure/go-amqp/blob/main/_autodocs/03-sender.md Sends a message and returns immediately after transmission, providing a receipt for later settlement confirmation. Use this when you want to send messages concurrently without blocking on each individual send. ```go receipt, err := sender.SendWithReceipt(context.TODO(), msg, nil) if err != nil { return err } // Do other work... state, err := receipt.Wait(context.TODO()) if err != nil { return err } log.Printf("message settled with state: %T", state) ``` -------------------------------- ### Open a New AMQP Session with Options Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Opens a new AMQP session with custom options, such as maximum links. Use context to control the operation's deadline and cancellation. ```go opts := &amqp.SessionOptions{ MaxLinks: 100, } session, err := conn.NewSession(context.TODO(), opts) if err != nil { return err } ``` -------------------------------- ### Get sender address Source: https://github.com/azure/go-amqp/blob/main/_autodocs/03-sender.md Retrieves the target address of the AMQP link. Useful for verifying the destination of messages. ```go addr := sender.Address() log.Printf("Sending to: %s", addr) ``` -------------------------------- ### Configure AMQP Receiver with Manual Credit and Copy Mode Source: https://github.com/azure/go-amqp/blob/main/_autodocs/08-configuration.md Set up a receiver with a specific name, manual credit management (credit = -1), configuration durability, custom properties, and browse mode for messages. This is useful when you need fine-grained control over message consumption and want to inspect messages without consuming them. ```go opts := &amqp.ReceiverOptions{ Name: "orders-receiver", Credit: -1, // Manual credit management Durability: amqp.DurabilityConfiguration, Properties: map[string]any{ "x-priority": 10, }, SourceDistributionMode: amqp.SourceDistributionModeCopy, // Browse messages OnDeliveryStateChanged: func(msg *amqp.Message, state amqp.DeliveryState) { log.Printf("Message %s delivery state changed: %T", msg.DeliveryTag, state) }, } receiver, err := session.NewReceiver(context.TODO(), "orders", opts) if err != nil { return err } // Manually manage credit if err := receiver.IssueCredit(50); err != nil { return err } ``` -------------------------------- ### Get sender link name Source: https://github.com/azure/go-amqp/blob/main/_autodocs/03-sender.md Retrieves the name of the AMQP link associated with the sender. Useful for logging or debugging. ```go log.Printf("Sender link: %s", sender.LinkName()) ``` -------------------------------- ### TLS/SSL Configuration Source: https://github.com/azure/go-amqp/blob/main/_autodocs/MANIFEST.md Illustrates how to configure TLS/SSL for secure AMQP connections. This is essential for encrypted communication over networks. ```go tlsConfig, err := amqp.NewClientTLSConfig( "/path/to/client.crt", "/path/to/client.key", "/path/to/ca.crt", ) conn, err := amqp.Dial("amqps://localhost:5671/", amqp.ConnOptions{ TLSConfig: tlsConfig, }) ``` -------------------------------- ### Establish AMQP Connection with Explicit Options Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Configure connection parameters like `ContainerID`, `SASLType`, `IdleTimeout`, and `MaxSessions` by passing a `*amqp.ConnOptions` struct to `amqp.Dial`. ```go opts := &amqp.ConnOptions{ ContainerID: "my-app-instance-1", SASLType: amqp.SASLTypePlain("username", "password"), IdleTimeout: 2 * time.Minute, MaxSessions: 10, } conn, err := amqp.Dial(context.TODO(), "amqps://mybroker.example.com", opts) if err != nil { return err } ``` -------------------------------- ### Get Session Properties Source: https://github.com/azure/go-amqp/blob/main/_autodocs/02-session.md Retrieves the properties sent by the peer in the Begin frame. Returns nil if no properties were sent. ```go props := session.Properties() if props != nil { for key, val := range props { log.Printf("%s = %v", key, val) } } ``` -------------------------------- ### ExpiryPolicy Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Specifies when the expiry timer of a terminus starts counting down. Constants include LinkDetach, SessionEnd, ConnectionClose, and Never. ```APIDOC ## ExpiryPolicy ### Description Specifies when the expiry timer of a terminus starts counting down. ### Constants - **ExpiryPolicyLinkDetach** (`encoding.ExpiryLinkDetach`): Expiry timer starts when the link is detached. - **ExpiryPolicySessionEnd** (`encoding.ExpirySessionEnd`): Expiry timer starts when the associated session ends. - **ExpiryPolicyConnectionClose** (`encoding.ExpiryConnectionClose`): Expiry timer starts when the connection closes. - **ExpiryPolicyNever** (`encoding.ExpiryNever`): Terminus never expires. ### Default ExpirySessionEnd ### Example ```go opts := &amqp.ReceiverOptions{ ExpiryPolicy: amqp.ExpiryPolicyConnectionClose, ExpiryTimeout: 300, // seconds } ``` ``` -------------------------------- ### Configure Filtered AMQP Receiver with Manual Credit Source: https://github.com/azure/go-amqp/blob/main/_autodocs/08-configuration.md Create a receiver with specific filters and manual credit management. Use `Credit: -1` for manual control and `IssueCredit`/`DrainCredit` to manage message flow. ```go opts := &amqp.ReceiverOptions{ Name: "filtered-receiver", Credit: -1, // Manual Filters: []amqp.LinkFilter{ amqp.NewSelectorFilter("status = 'pending' AND priority > 3"), }, OnDeliveryStateChanged: func(msg *amqp.Message, state amqp.DeliveryState) { log.Printf("Delivery state: %T", state) }, } receiver, _ := session.NewReceiver(context.TODO(), "tasks", opts) // Issue initial credit receiver.IssueCredit(50) // Drain and reissue as needed time.Sleep(10 * time.Second) receiver.DrainCredit(context.TODO(), nil) receiver.IssueCredit(100) ``` -------------------------------- ### Configure Session with Max Links Source: https://github.com/azure/go-amqp/blob/main/_autodocs/02-session.md Creates a new session with a specified maximum number of links. The default is the maximum uint32 value. ```go opts := &amqp.SessionOptions{ MaxLinks: 50, } session, err := conn.NewSession(context.TODO(), opts) if err != nil { return err } ``` -------------------------------- ### Handle Connection Refused Error Source: https://github.com/azure/go-amqp/blob/main/_autodocs/07-errors.md Demonstrates how to catch and log a connection failure when the broker address is invalid or the broker is not listening. ```go conn, err := amqp.Dial(context.TODO(), "amqps://invalid.example.com:9999", nil) if err != nil { // err is *ConnError with inner = dial error log.Printf("connection failed: %v", err) } ``` -------------------------------- ### Get Receiver Peer Link Properties Source: https://github.com/azure/go-amqp/blob/main/_autodocs/04-receiver.md Retrieve properties sent by the peer in the Attach frame. Returns nil if no properties were sent. ```go if props := receiver.Properties(); props != nil { for k, v := range props { log.Printf("peer property %s = %v", k, v) } } ``` -------------------------------- ### Get Receiver Link Address Source: https://github.com/azure/go-amqp/blob/main/_autodocs/04-receiver.md Retrieve the source address of the AMQP link for the receiver. Returns an empty string if the address is not set. ```go addr := receiver.Address() log.Printf("Receiving from: %s", addr) ``` -------------------------------- ### Package Import Source: https://github.com/azure/go-amqp/blob/main/_autodocs/INDEX.md Import the root amqp package for all public API access. Internal implementation details are located in subpackages. ```go import "github.com/Azure/go-amqp" ``` -------------------------------- ### Monitor AMQP Connection and Reconnect Source: https://github.com/azure/go-amqp/blob/main/_autodocs/09-examples.md This snippet shows how to establish an AMQP connection, monitor its state in the background, and automatically retry connection if it fails. It also includes basic message sending within a session. ```Go func monitorConnection(ctx context.Context, broker string) error { for { conn, err := amqp.Dial(ctx, broker, &amqp.ConnOptions{ SASLType: amqp.SASLTypePlain("user", "pass"), }) if err != nil { log.Printf("Connection failed: %v, retrying in 5s...", err) select { case <-time.After(5 * time.Second): continue case <-ctx.Done(): return ctx.Err() } } log.Println("Connected to broker") // Monitor connection in background go func() { <-conn.Done() if err := conn.Err(); err != nil { if connErr, ok := err.(*amqp.ConnError); ok && connErr.RemoteErr != nil { log.Printf("Connection closed by peer: %s", connErr.RemoteErr.Condition) } else { log.Printf("Connection lost: %v", err) } } }() // Use connection session, _ := conn.NewSession(ctx, nil) sender, _ := session.NewSender(ctx, "queue", nil) // Send messages until connection closes for i := 0; i < 100; i++ { msg := amqp.NewMessage([]byte(fmt.Sprintf("msg-%d", i))) if err := sender.Send(ctx, msg, nil); err != nil { log.Printf("Send error: %v", err) sender.Close(ctx) session.Close(ctx) conn.Close() break } select { case <-time.After(1 * time.Second): case <-ctx.Done(): sender.Close(ctx) session.Close(ctx) conn.Close() return nil } } } } ``` -------------------------------- ### Connect to AMQP Broker Source: https://github.com/azure/go-amqp/blob/main/README.md Connect to an AMQP 1.0 broker using amqp.Dial(). This establishes an amqp.Conn. Ensure the broker address is correct. ```go conn, err := amqp.Dial(context.TODO(), "amqp[s]://", nil) if err != nil { // handle error } ``` -------------------------------- ### Establish AMQP Connection with Dial Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Use `amqp.Dial` to establish a new AMQP connection to a broker. Provide the broker address and optional connection options. The context controls the connection attempt. ```go conn, err := amqp.Dial(context.TODO(), "amqps://mybroker.example.com:5671", nil) if err != nil { return err } deffer conn.Close() ``` -------------------------------- ### Get Receiver Link Name Source: https://github.com/azure/go-amqp/blob/main/_autodocs/04-receiver.md Retrieve the name of the AMQP link associated with the receiver. Returns an empty string if the link name is not set. ```go log.Printf("Receiver link: %s", receiver.LinkName()) ``` -------------------------------- ### Get First Data Payload Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Retrieves the first binary payload from the Data field of a message. Returns nil if the Data field is empty. ```go func (m *Message) GetData() []byte ``` ```go payload := msg.GetData() if payload != nil { log.Printf("Payload: %s", string(payload)) } ``` -------------------------------- ### Implement AMQP Request-Reply Pattern Source: https://github.com/azure/go-amqp/blob/main/_autodocs/08-configuration.md Set up a sender for requests and a receiver for replies using dynamic addresses. This pattern is useful for synchronous request-response interactions. ```go // Sender senderOpts := &amqp.SenderOptions{ Name: "request-sender", } sender, _ := session.NewSender(context.TODO(), "requests", senderOpts) // Receiver for replies replyOpts := &amqp.ReceiverOptions{ Name: "reply-receiver", Credit: 1, DynamicAddress: true, } replyLink, _ := session.NewReceiver(context.TODO(), "", replyOpts) replyAddr := replyLink.Address() // Send request with reply-to msg := amqp.NewMessage([]byte(`{"action":"compute"}`)) msg.Properties = &amqp.MessageProperties{ ReplyTo: &replyAddr, } sender.Send(context.TODO(), msg, nil) ``` -------------------------------- ### Create AMQP Message Instance Source: https://github.com/azure/go-amqp/blob/main/README.md Instantiate an amqp.Message directly and populate its fields. The Data field is commonly used for message content. ```go msg := &amqp.Message{ // populate fields (Data is the most common) } ``` -------------------------------- ### SASL Mechanisms Configuration Source: https://github.com/azure/go-amqp/blob/main/_autodocs/MANIFEST.md Demonstrates how to configure different SASL mechanisms for AMQP connections. This includes PLAIN, ANONYMOUS, EXTERNAL, and XOAUTH2. ```go conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/", amqp.ConnOptions{ SASLType: amqp.SASLTypePlain(), }) conn, err := amqp.Dial("amqp://localhost:5672/", amqp.ConnOptions{ SASLType: amqp.SASLTypeAnonymous(), }) conn, err := amqp.Dial("amqps://localhost:5671/", amqp.ConnOptions{ SASLType: amqp.SASLTypeExternal(), }) conn, err := amqp.Dial("amqps://user:pass@localhost:5671/", amqp.ConnOptions{ SASLType: amqp.SASLTypeXOAUTH2("user", "pass"), }) ``` -------------------------------- ### Get Delivery Tag from Send Receipt Source: https://github.com/azure/go-amqp/blob/main/_autodocs/03-sender.md Retrieve the delivery tag for a sent message from its SendReceipt. The delivery tag is a unique identifier for the message on the link. ```go receipt, _ := sender.SendWithReceipt(context.TODO(), msg, nil) tag := receipt.DeliveryTag() log.Printf("Message delivery tag: %x", tag) ``` -------------------------------- ### Get peer link properties Source: https://github.com/azure/go-amqp/blob/main/_autodocs/03-sender.md Retrieves properties sent by the peer during the link establishment (Attach frame). Useful for inspecting peer capabilities or configuration. ```go if props := sender.Properties(); props != nil { for k, v := range props { log.Printf("peer property %s = %v", k, v) } } ``` -------------------------------- ### Create AMQP Message with Constructor Source: https://github.com/azure/go-amqp/blob/main/README.md Use the amqp.NewMessage() constructor for convenience. It sets the provided byte slice as the first entry in the Data field. ```go msg := amqp.NewMessage(/* some []byte */) ``` -------------------------------- ### Get maximum message size Source: https://github.com/azure/go-amqp/blob/main/_autodocs/03-sender.md Retrieves the maximum message size accepted by the peer. Use this to validate message sizes before sending to avoid rejections. ```go maxSize := sender.MaxMessageSize() if maxSize > 0 && len(data) > int(maxSize) { return fmt.Errorf("message exceeds maximum size of %d", maxSize) } ``` -------------------------------- ### Handle SessionError after NewSession Source: https://github.com/azure/go-amqp/blob/main/_autodocs/07-errors.md Illustrates how to detect and process a SessionError when creating a new session. This example checks if the error is a SessionError and if it includes a RemoteErr from the AMQP peer. ```go session, err := conn.NewSession(context.TODO(), &amqp.SessionOptions{ MaxLinks: 0, // Invalid value }) if err != nil { if sessErr, ok := err.(*amqp.SessionError); ok && sessErr.RemoteErr != nil { log.Printf("Session error from peer: %s", sessErr.RemoteErr.Condition) } return err } ``` -------------------------------- ### Check for Rejected Delivery State with Error Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Demonstrates checking for a rejected delivery state and accessing optional error details. ```go if rejected, ok := state.(*amqp.StateRejected); ok { if rejected.Error != nil { log.Printf("message rejected: %s", rejected.Error.Condition) } } ``` -------------------------------- ### Handle LinkError after Receiver Receive Source: https://github.com/azure/go-amqp/blob/main/_autodocs/07-errors.md Provides an example of how to identify and react to a LinkError when receiving messages. It distinguishes between a link detached by the peer (with a RemoteErr) and a link closed locally. ```go msg, err := receiver.Receive(context.TODO(), nil) if err != nil { if linkErr, ok := err.(*amqp.LinkError); ok { if linkErr.RemoteErr != nil { log.Printf("Link detached by peer: %s", linkErr.RemoteErr.Condition) } else { log.Printf("Link closed locally: %v", linkErr.Error()) } } return err } ``` -------------------------------- ### Open a New AMQP Session Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Opens a new AMQP session on an existing connection. Use context to control the operation's deadline and cancellation. Pass nil for default session options. ```go session, err := conn.NewSession(context.TODO(), nil) if err != nil { return err } defer session.Close(context.TODO()) ``` -------------------------------- ### Get Prefetched Message Source: https://github.com/azure/go-amqp/blob/main/_autodocs/04-receiver.md Retrieves the next message from the prefetch cache without blocking. Returns nil if the cache is empty. Useful for a non-blocking check before attempting a blocking receive. ```go for { msg := receiver.Prefetched() if msg == nil { // Check for buffered message msg, err := receiver.Receive(context.TODO(), nil) if err != nil { return err } processMessage(msg) } else { processMessage(msg) } } ``` -------------------------------- ### Configure AMQP Connection Options Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Defines the structure for configuring an AMQP connection, including container ID, host name, timeouts, frame size, and TLS settings. ```go type ConnOptions struct { ContainerID string HostName string IdleTimeout time.Duration MaxFrameSize uint32 MaxSessions uint16 Properties map[string]any SASLType SASLType TLSConfig *tls.Config WriteTimeout time.Duration } ``` -------------------------------- ### Construct AMQP Message with Annotations Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Creates an AMQP message that includes custom key-value annotations. ```go msg := &amqp.Message{ Annotations: amqp.Annotations{ "user-id": "alice", "tenant": "acme", }, Data: [][]byte{[]byte("payload")}, } ``` -------------------------------- ### Construct AMQP Message with Properties Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Builds an AMQP message with standard properties like MessageID, Subject, and ContentType, along with binary data. ```go subject := "important" msg := &amqp.Message{ Properties: &amqp.MessageProperties{ MessageID: "msg-123", Subject: &subject, ContentType: ptrs.String("text/plain"), }, Data: [][]byte{[]byte("important message")}, } ``` -------------------------------- ### Implement Request-Reply with Dynamic Reply-To Address Source: https://github.com/azure/go-amqp/blob/main/_autodocs/09-examples.md This snippet shows how to implement the request-reply pattern. It dynamically creates a reply-to address for the receiver and sends a request with a correlation ID. Ensure the receiver is set up to handle dynamic addresses. ```go func requestReply(ctx context.Context, session *amqp.Session) (string, error) { // Create reply-to address dynamically replyOpts := &amqp.ReceiverOptions{ DynamicAddress: true, Credit: 1, } replyReceiver, err := session.NewReceiver(ctx, "", replyOpts) if err != nil { return "", err } defer replyReceiver.Close(ctx) replyAddr := replyReceiver.Address() log.Printf("Reply address: %s", replyAddr) // Create sender sender, err := session.NewSender(ctx, "request-queue", nil) if err != nil { return "", err } defer sender.Close(ctx) // Send request correlationID := fmt.Sprintf("req-%d", time.Now().UnixNano()) msg := &amqp.Message{ Properties: &amqp.MessageProperties{ MessageID: correlationID, ReplyTo: &replyAddr, CorrelationID: correlationID, }, Data: [][]byte{[]byte(`{"action":"calculate","value":42}`)}, } if err := sender.Send(ctx, msg, nil); err != nil { return "", err } log.Printf("Request sent with correlation ID: %s", correlationID) // Wait for reply replyCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() reply, err := replyReceiver.Receive(replyCtx, nil) if err != nil { return "", err } if err := replyReceiver.AcceptMessage(ctx, reply); err != nil { return "", err } return string(reply.GetData()), nil } ``` -------------------------------- ### Get Receiver Link Source Filter Value Source: https://github.com/azure/go-amqp/blob/main/_autodocs/04-receiver.md Retrieve the value of a specific filter applied to the link's source. Use this to inspect filters like 'apache.org:selector-filter:string'. Returns nil if the filter is not found. ```go if filterVal := receiver.LinkSourceFilterValue("apache.org:selector-filter:string"); filterVal != nil { log.Printf("Selector filter: %s", filterVal) } ``` -------------------------------- ### Open New Sender Link with Options Source: https://github.com/azure/go-amqp/blob/main/_autodocs/02-session.md Opens a new sender link with custom options, such as specifying a sender name or settlement mode. This allows for more control over the sender's behavior. ```go opts := &amqp.SenderOptions{ Name: "my-sender-1", SettlementMode: &amqp.SenderSettleModeMixed, } sender, err := session.NewSender(context.TODO(), "my-queue", opts) if err != nil { return err } ``` -------------------------------- ### Get AMQP Connection Error State Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Use `conn.Err()` to retrieve the connection's error state. It returns `nil` if the connection is open, or a `*ConnError` if closed, indicating the reason for termination (clean shutdown, remote error, or internal failure). ```go if err := conn.Err(); err != nil { log.Printf("connection error: %v", err) if connErr, ok := err.(*amqp.ConnError); ok && connErr.RemoteErr != nil { log.Printf("remote error: %v", connErr.RemoteErr) } } ``` -------------------------------- ### Configure AMQP Sender Options Source: https://github.com/azure/go-amqp/blob/main/_autodocs/08-configuration.md Configure a new AMQP sender with various options such as name, durability, expiry, settlement mode, and custom properties. Use this when you need to specify advanced sender behaviors. ```go opts := &amqp.SenderOptions{ Name: "orders-sender", Durability: amqp.DurabilityConfiguration, ExpiryPolicy: amqp.ExpiryPolicyConnectionClose, ExpiryTimeout: 300, // 5 minutes SettlementMode: &amqp.SenderSettleModeMixed, Properties: map[string]any{ "x-routing-key": "orders.created", "x-origin": "order-service", }, TargetCapabilities: []string{"topic-selector"}, OnLinkStateProperties: func(props map[string]any) { log.Printf("Link properties updated: %v", props) }, } sender, err := session.NewSender(context.TODO(), "orders", opts) ``` -------------------------------- ### Handle Queue Not Found Error Source: https://github.com/azure/go-amqp/blob/main/_autodocs/07-errors.md Illustrates how to identify and handle errors when attempting to attach to a non-existent queue. ```go receiver, err := session.NewReceiver(context.TODO(), "nonexistent-queue", nil) if err != nil { if linkErr, ok := err.(*amqp.LinkError); ok && linkErr.RemoteErr != nil { if linkErr.RemoteErr.Condition == amqp.ErrCondNotFound { log.Println("queue not found") } } return err } ``` -------------------------------- ### Create Annotations Map Source: https://github.com/azure/go-amqp/blob/main/_autodocs/06-types.md Create an Annotations map for key-value pairs with restricted key types (string, int, int64). String keys are encoded as AMQP symbols. ```go annotations := amqp.Annotations{ "user": "alice", "tenant": 123, } ``` -------------------------------- ### Establish AMQP Connection over Existing Network Connection Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Use `amqp.NewConn` to establish an AMQP connection over an already established `net.Conn`. The `Conn` takes ownership of the provided network connection. ```go netConn, err := net.Dial("tcp", "mybroker.example.com:5672") if err != nil { return err } conn, err := amqp.NewConn(context.TODO(), netConn, nil) if err != nil { netConn.Close() return err } deffer conn.Close() ``` -------------------------------- ### Create AMQP Session Source: https://github.com/azure/go-amqp/blob/main/README.md Create an amqp.Session from an existing amqp.Conn using Conn.NewSession(). Sessions are used to manage message flows. ```go session, err := conn.NewSession(context.TODO(), nil) if err != nil { // handle error } ``` -------------------------------- ### Construct AMQP Message with Application Properties Source: https://github.com/azure/go-amqp/blob/main/_autodocs/05-message.md Creates an AMQP message that includes application-specific properties as a map of string keys to any type of value. ```go msg := &amqp.Message{ ApplicationProperties: map[string]any{ "order_id": 12345, "customer": "acme-corp", "total": 199.99, }, Data: [][]byte{[]byte(`{"status":"pending"}`)}, } ``` -------------------------------- ### ConnOptions Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Configuration struct for establishing an AMQP connection. ```APIDOC ## ConnOptions ### Description Configuration for an AMQP connection. ### Fields - **ContainerID** (string) - Optional - A unique identifier for this client. If empty, a random 40-character string is generated. - **HostName** (string) - Optional - The hostname sent in the AMQP Open frame and used as the TLS ServerName if not otherwise set. If empty, it is inferred from the connection address. - **IdleTimeout** (time.Duration) - Optional - The maximum period between receiving frames from the peer. Pass a value less than zero to disable idle timeout. Default: 1 minute. - **MaxFrameSize** (uint32) - Optional - The maximum frame size the connection will accept. Must be at least 512. Default: 65536. - **MaxSessions** (uint16) - Optional - The maximum number of sessions allowed on this connection. Must be greater than zero. Default: 65536. - **Properties** (map[string]any) - Optional - Custom properties to send to the peer in the Open frame. Keys are converted to AMQP symbols. - **SASLType** (SASLType) - Optional - The SASL authentication mechanism to use (e.g., `SASLTypePlain("user", "pass")`). If nil, SASL is not negotiated. - **TLSConfig** (*tls.Config) - Optional - TLS configuration for secure connections. Used only if the URL scheme is `amqp://` (not `amqps://`). If nil, a default config is created with ServerName set to HostName. - **WriteTimeout** (time.Duration) - Optional - The write deadline per frame when no caller-provided context is available. A value less than zero means no timeout. Default: 30 seconds. ``` -------------------------------- ### Session Options Struct Source: https://github.com/azure/go-amqp/blob/main/_autodocs/08-configuration.md Defines the structure for configuring AMQP session options. Used with Conn.NewSession(). ```go type SessionOptions struct { MaxLinks uint32 } ``` -------------------------------- ### Configure TLSConfig for Connection Source: https://github.com/azure/go-amqp/blob/main/_autodocs/08-configuration.md Provides TLS configuration for the connection, used when the URL scheme is 'amqp://'. If nil, a default config is created. ```go tlsConfig := &tls.Config{ InsecureSkipVerify: false, MinVersion: tls.VersionTLS12, CipherSuites: []uint16{ ls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, }, } opts := &amqp.ConnOptions{ TLSConfig: tlsConfig, } ``` ```go cert, err := tls.LoadX509KeyPair("client.crt", "client.key") if err != nil { return err } tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, } opts := &amqp.ConnOptions{ TLSConfig: tlsConfig, } ``` -------------------------------- ### Connect to AMQP Broker Source: https://github.com/azure/go-amqp/blob/main/_autodocs/INDEX.md Establishes a connection to an AMQP broker using SASL PLAIN authentication. Ensure the broker address and credentials are correct. The connection should be closed when no longer needed. ```go conn, err := amqp.Dial(context.TODO(), "amqps://broker.example.com", &amqp.ConnOptions{ SASLType: amqp.SASLTypePlain("username", "password"), }) if err != nil { return err } deffer conn.Close() ``` -------------------------------- ### Basic Send and Receive AMQP Message Source: https://github.com/azure/go-amqp/blob/main/_autodocs/09-examples.md Connects to an AMQP broker, sends a message, and then receives and accepts it. Ensure you have a running AMQP broker and replace placeholder connection details. ```go package main import ( "context" "log" "time" "github.com/Azure/go-amqp" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() // Connect to broker conn, err := amqp.Dial(ctx, "amqps://broker.example.com", &amqp.ConnOptions{ SASLType: amqp.SASLTypePlain("username", "password"), }) if err != nil { log.Fatalf("Dial error: %v", err) } defer conn.Close() // Create session session, err := conn.NewSession(ctx, nil) if err != nil { log.Fatalf("NewSession error: %v", err) } defer session.Close(ctx) // Create sender sender, err := session.NewSender(ctx, "my-queue", nil) if err != nil { log.Fatalf("NewSender error: %v", err) } defer sender.Close(ctx) // Send message msg := amqp.NewMessage([]byte("Hello, AMQP!")) if err := sender.Send(ctx, msg, nil); err != nil { log.Fatalf("Send error: %v", err) } log.Println("Message sent successfully") // Create receiver receiver, err := session.NewReceiver(ctx, "my-queue", nil) if err != nil { log.Fatalf("NewReceiver error: %v", err) } defer receiver.Close(ctx) // Receive message msg, err = receiver.Receive(ctx, nil) if err != nil { log.Fatalf("Receive error: %v", err) } log.Printf("Message received: %s", string(msg.GetData())) // Accept message if err := receiver.AcceptMessage(ctx, msg); err != nil { log.Fatalf("AcceptMessage error: %v", err) } } ``` -------------------------------- ### SessionOptions Source: https://github.com/azure/go-amqp/blob/main/_autodocs/02-session.md Configuration for an AMQP session, including the maximum number of links allowed. ```APIDOC ## SessionOptions ### Description Configuration for an AMQP session, including the maximum number of links allowed. ### Fields - **MaxLinks** (uint32) - Default: 4294967295 - The maximum number of links (senders and receivers) allowed on this session. Minimum is 1. ### Example ```go opts := &amqp.SessionOptions{ MaxLinks: 50, } session, err := conn.NewSession(context.TODO(), opts) if err != nil { return err } ``` ``` -------------------------------- ### Send multiple messages concurrently Source: https://github.com/azure/go-amqp/blob/main/_autodocs/03-sender.md Demonstrates sending many messages concurrently using `SendWithReceipt` and then waiting for all of them to be confirmed. This pattern is efficient for high-throughput scenarios. ```go var receipts []amqp.SendReceipt for i := 0; i < 100; i++ { msg := amqp.NewMessage([]byte(fmt.Sprintf("message %d", i))) receipt, err := sender.SendWithReceipt(context.TODO(), msg, nil) if err != nil { return err } receipts = append(receipts, receipt) } // Wait for all to be confirmed for _, receipt := range receipts { if _, err := receipt.Wait(context.TODO()); err != nil { return err } } ``` -------------------------------- ### Create AMQP Receiver in Go Source: https://github.com/azure/go-amqp/blob/main/README.md Create an amqp.Receiver to receive messages after an amqp.Session has been established. This requires the name of the peer's sending terminus. ```go receiver, err := session.NewReceiver(context.TODO(), "", nil) ``` -------------------------------- ### Monitor Connection Closure Source: https://github.com/azure/go-amqp/blob/main/_autodocs/07-errors.md This snippet shows how to monitor the connection's Done channel to detect and log connection closures and associated errors. ```go conn, _ := amqp.Dial(context.TODO(), "amqps://broker.example.com", nil) // Connection is running in background go func() { <-conn.Done() if err := conn.Err(); err != nil { if connErr, ok := err.(*amqp.ConnError); ok && connErr.RemoteErr != nil { log.Printf("Connection lost: %s", connErr.RemoteErr.Condition) } } }() ``` -------------------------------- ### Manual Credit Management for Receiver Source: https://github.com/azure/go-amqp/blob/main/_autodocs/INDEX.md Configure a receiver with manual credit management to gain fine-grained control over message arrival. Issue a specific number of credits to the receiver after it's created. ```go opts := &amqp.ReceiverOptions{ Credit: -1, // Manual } receiver, _ := session.NewReceiver(ctx, "queue", opts) receiver.IssueCredit(50) ``` -------------------------------- ### Dial Source: https://github.com/azure/go-amqp/blob/main/_autodocs/01-connection.md Establishes a new AMQP connection to a broker using a connection string. ```APIDOC ## Dial Establishes a new AMQP connection to a broker. ### Description This function establishes a new AMQP connection to a specified broker address. It supports various URL formats for connection strings, including SASL authentication credentials directly within the URL. Optional connection configurations can be provided via `ConnOptions`. ### Method `Dial` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context controlling the connection establishment. If the context is cancelled or its deadline expires, the connection attempt is aborted. - **addr** (string) - Required - The address of the AMQP broker in the format `amqp[s]://host[:port]` or `amqp+ssl://host[:port]`. If no port is provided, 5672 is used for `amqp` and 5671 for `amqps` or `amqp+ssl`. If username and password are provided in the URL (e.g., `amqp://user:pass@host`), they are used as SASL PLAIN credentials. - **opts** (*ConnOptions) - Optional - Optional connection configuration. Pass nil to accept defaults. ### Response #### Success Response - `*Conn` - An initialized AMQP connection ready for use #### Error Response - `error` - Non-nil if connection establishment fails (invalid URL, authentication failure, connection refused, context deadline exceeded, etc.) ### Request Example ```go conn, err := amqp.Dial(context.TODO(), "amqps://mybroker.example.com:5671", nil) if err != nil { return err } defer conn.Close() ``` ### With SASL authentication via URL: ```go conn, err := amqp.Dial(context.TODO(), "amqps://username:password@mybroker.example.com", nil) if err != nil { return err } ``` ### With explicit options: ```go opts := &amqp.ConnOptions{ ContainerID: "my-app-instance-1", SASLType: amqp.SASLTypePlain("username", "password"), IdleTimeout: 2 * time.Minute, MaxSessions: 10, } conn, err := amqp.Dial(context.TODO(), "amqps://mybroker.example.com", opts) if err != nil { return err } ``` ```