search
HomeBackend DevelopmentGolangEvent-driven design with Log Events and RabbitMQ in Golang

Event-driven design with Log Events and RabbitMQ in Golang

The adoption of event-driven architecture is on the rise as teams pursue more adaptable, scalable, and agile solutions to meet the requirements of contemporary applications. Event-driven architectures support real-time updates and streamline integration across different systems by enabling communication through standardized and structured events.

In a previous blog post, I discussed how webhooks in Auth0 can transmit events, thereby leveraging these events to initiate logic execution. In this article, I will delve into the technical aspects of this architecture and demonstrate how Go (Golang) can be utilized to construct such a system.

Main components:

Let's first have a look at the main components that drive this system.

Log Events:

Auth0 has log events associated with every activity at a tenant level. These events can be used for monitoring or audit purposes. The codes for each event can be checked out here

Webhooks:

We use auth0 webhooks to deliver filtered events to our producer. We filter these events since we are interested in only a handful.

RabbitMQ

RabbitMQ supports multiple messaging protocols, and the one we use to route messages is the Advanced Messaging Queueing Protocol (AMQP). AMQP has three main entities – Queues, Exchanges and Bindings.

Behind the scenes

When an event is triggered in Auth0, it's immediately sent via webhook to our publisher, which then publishes it based on the event type. Once published, the event goes to an exchange. The exchange directs the message to connected queues, where consumers receive it. To enable this process, we establish a channel. This channel allows us to publish messages to exchange and declare queues for subscription.

To create a new queue, we utilize the QueueDeclare function provided by the package on the channel, specifying our desired queue properties. With the queue created, we can use the channel's Publish function to send a message.

Next, we create a consumer that connects to our RabbitMQ and establishes a channel for communication. Using this channel, we can consume messages using the Consume method defined for it.

Groundwork

We use golang-auth0 management package to work on the log events and for the queue actions we use github.com/rabbitmq/amqp091-go.

Given below are the snippets:

Publishing:

A detailed structure of the log can be found here

    for _, auth0log := range payload.Logs {

        switch auth0log.Data.Type {
        case "slo":
            _, err = c.Publish(ctx, PublishRequest{
                ---your logic---
            })

        case "ss":
            _, err = c.Publish(ctx,PublishRequest{
                    -- your logic -----
                })

        }
    }

Exchange:

    if consumeOptions.BindingExchange != "" {
        for _, routingKey := range routingKeys {
            err = consumer.chManager.channel.QueueBind(
                queue,
                routingKey,
                consumeOptions.BindingExchange,
                consumeOptions.BindingNoWait,
                tableToAMQPTable(consumeOptions.BindingArgs),
            )
            if err != nil {
                return err
            }
        }
    }

Consuming:

func (c *Client) Consume() {
    err := c.consumer.StartConsuming(
        func(ctx context.Context, d queue.Delivery) bool {
            err := c.processMessages(ctx, d.Body, d.Exchange)
            if err != nil {
                c.log.Error().Ctx(ctx).Err(err).Str("exchange", d.Exchange).Msg("failed publishing")
                return nack // send to dlx
            }
            return ack // message acknowledged
        },
        c.queueName,
        []string{c.queueRoutingKey},
        func(opts *queue.ConsumeOptions) {
            opts.BindingExchange = c.queueBidingExchange
            opts.QueueDurable = true
            opts.QueueArgs = map[string]interface{}{
                "x-dead-letter-exchange": c.queueBidingExchangeDlx,
            }
        },
    )
    if err != nil {
        c.log.Fatal().Err(err).Msg("consumer: Failed to StartConsuming")
    }

    // block main thread so consumers run forever
    forever := make(chan struct{})
    



<p>Thus, by leveraging webhooks in Auth0 to trigger events and employing RabbitMQ for reliable message queuing and delivery, we can build scalable and responsive applications. This approach not only enhances flexibility but also supports seamless event processing, enabling efficient handling of asynchronous operations. </p>

<p>I hope this article was helpful and can prove to be beneficial in your event-driven journey.</p>

<p>Happy coding :)</p>


          

            
        

The above is the detailed content of Event-driven design with Log Events and RabbitMQ in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering Go Strings: A Deep Dive into the 'strings' PackageMastering Go Strings: A Deep Dive into the 'strings' PackageMay 12, 2025 am 12:05 AM

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

'encoding/binary' Package in Go: Your Go-To for Binary Operations'encoding/binary' Package in Go: Your Go-To for Binary OperationsMay 12, 2025 am 12:03 AM

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Go Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageGo Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageMay 12, 2025 am 12:02 AM

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.

How do you use the 'strings' package to manipulate strings in Go?How do you use the 'strings' package to manipulate strings in Go?May 12, 2025 am 12:01 AM

You can use the "strings" package in Go to manipulate strings. 1) Use strings.TrimSpace to remove whitespace characters at both ends of the string. 2) Use strings.Split to split the string into slices according to the specified delimiter. 3) Merge string slices into one string through strings.Join. 4) Use strings.Contains to check whether the string contains a specific substring. 5) Use strings.ReplaceAll to perform global replacement. Pay attention to performance and potential pitfalls when using it.

How to use the 'bytes' package to manipulate byte slices in Go (step by step)How to use the 'bytes' package to manipulate byte slices in Go (step by step)May 12, 2025 am 12:01 AM

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

GO bytes package: What are the alternatives?GO bytes package: What are the alternatives?May 11, 2025 am 12:11 AM

ThealternativestoGo'sbytespackageincludethestringspackage,bufiopackage,andcustomstructs.1)Thestringspackagecanbeusedforbytemanipulationbyconvertingbytestostringsandback.2)Thebufiopackageisidealforhandlinglargestreamsofbytedataefficiently.3)Customstru

Manipulating Byte Slices in Go: The Power of the 'bytes' PackageManipulating Byte Slices in Go: The Power of the 'bytes' PackageMay 11, 2025 am 12:09 AM

The"bytes"packageinGoisessentialforefficientlymanipulatingbyteslices,crucialforbinarydata,networkprotocols,andfileI/O.ItoffersfunctionslikeIndexforsearching,Bufferforhandlinglargedatasets,Readerforsimulatingstreamreading,andJoinforefficient

Go Strings Package: A Comprehensive Guide to String ManipulationGo Strings Package: A Comprehensive Guide to String ManipulationMay 11, 2025 am 12:08 AM

Go'sstringspackageiscrucialforefficientstringmanipulation,offeringtoolslikestrings.Split(),strings.Join(),strings.ReplaceAll(),andstrings.Contains().1)strings.Split()dividesastringintosubstrings;2)strings.Join()combinesslicesintoastring;3)strings.Rep

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool