Why does my event run twice when data only fed once?

Issue

So i have trimmed my Go code below for better understanding as I am using libraries to implement this.

Basically what I am trying to do is receive a JSON text, trim it into a certain format and pass it over to createTicket function.

Everything works fine and my createTicket function creates it with the correct subject field from replyText, however createTicket runs almost 2-3x everytime I feed a JSON into my application and my debug print message prints few times.

On the backend createTicket will create a ticket on my system and 2-3 new tickets appear when I have only fed the system a JSON only once during my testing.

func handleMessage(bot *lark.Bot, msg *lark.EventV2MessageReceived, client *zendesk.Client) {
    query := msg.Message.Content
    //fmt.Println(query)
    var replyText ReplyText
    err := json.Unmarshal([]byte(query), &replyText)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(replyText.Text)

    client.CreateTicket(context.Background(), zendesk.Ticket{
        Subject:  replyText.Text,
        Priority: "P2",
        Comment: zendesk.TicketComment{
            Body: "testBody",
        },
    })

    //print("DEBUG: MSG HANDLED AND TICKET CREATED")
}

The code that calls handleMsg() function is through an API call below listening on my server. Basically just an event handler, So when I send a message to my application below it will do the necessary checks and I will pass the message received to the function as below.

r.POST("/", func(c *gin.Context) {
    if evt, ok := middleware.GetEvent(c); ok {
        if evt.Header.EventType == lark.EventTypeMessageReceived {
            if msg, err := evt.GetMessageReceived(); err == nil {
                fmt.Println(msg.Message.Content)
                handleMessage(bot, msg, client)
                c.JSON(http.StatusOK, gin.H{"status": "ok"})
            }
        }
    }
})

Solution

I was missing go in handleMessage(bot, msg, client)

It should be go handleMessage(bot, msg, client) to call the routine once.

This fixed my issue.

Answered By – tetekmaster

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.