Search code examples
azuregoazure-functionsazure-eventgrid

How to create an azure function app using grid event trigger with Go


I want to run an azure function when an Event Grid event is dispatched using golang. However i'm trying to test the function out but i'm getting a 500 when using curl to test out the endpoint.

  -X POST -H 'aeg-event-type: Notification' \
  -H "Content-Type: application/json" \
  -d @eventgridtriggerschema.json \
  'https://xxxxx.azurewebsites.net/runtime/webhooks/EventGrid?functionName=EventGridTrigger&code=xxxxxx' && echo

500

eventgridtriggerschema.json is a sample event Grid Tigger: https://learn.microsoft.com/en-us/azure/event-grid/event-schema#event-schema

Looking at the logs on the azure function side in log analytics, i dont see anything that jumps out as being wrong. I do see the requests I make using curl, but the exception doesn't really adds up to what is wrong or provide any insight on what i need to fix:

---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()

My go app is very basic since, i'm just trying to get endpoint working before implementing the logic:

func eventGridTriggerHandler(w http.ResponseWriter, r *http.Request) {
   log.Printf("Recieved message!")
}

func main() {
  listenAddr := ":8080"
  if val, ok := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT"); ok {
    listenAddr = ":" + val
  }
  http.HandleFunc("/api/EventGridTrigger", eventGridTriggerHandler)
  log.Printf("About to listen on %s. Go to http://127.0.0.1%s/", listenAddr, listenAddr)
  log.Fatal(http.ListenAndServe(listenAddr, nil))
}

My function.json:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "eventGridTrigger",
      "direction": "in",
      "name": "req"
    }
  ]
}

My host.json is the following (I was able to get a basic HttpTrigger working just fine, so I believe my host.json is correct, but i'm posting for posterity:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    },
    "fileLoggingMode": "always",
    "logLevel": {
        "default": "Information",
        "Host.Results": "Error",
        "Function": "Trace",
        "Host.Aggregator": "Trace"
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  },
  "customHandler": {
    "description": {
      "defaultExecutablePath": "handler",
      "workingDirectory": "",
      "arguments": []
    },
    "enableForwardingHttpRequest": true
  }
}

Can anyone help me out on why this go function app isn't working when using the eventGridTrigger? I was thinking of switching to python or something else, but I figured posting here to see if anyone has any thoughts and can point me in the right direction.

Appreciate the help in advance


Solution

  • I was thinking of switching to python or something else

    I tried the Event Grid trigger function in Go, but it didn't trigger. Then, I tried the Event Grid trigger function in Python (v1 model), and it successfully triggered the events.

    init.py :

    import json
    import logging
    
    from azure.functions import EventGridEvent
    
    def main(event: EventGridEvent):
        result = json.dumps({
            'id': event.id,
            'data': event.get_json(),
            'topic': event.topic,
            'subject': event.subject,
            'event_type': event.event_type,
        })
    
        logging.info('Python EventGrid trigger processed an event: %s', result)
    

    I deployed the function to an Azure Function App and created a subscription in an Azure Event Grid Topic with the endpoint set to the Azure Function.

    enter image description here

    Postman :

    https://kamxxxxxx.eventgrid.azure.net/api/events?api-version=2018-01-01
    

    Under Headers, added the EventGridTopicKey as shown below,

    aeg-sas-key :  <EventGridTopicKey>
    

    enter image description here

    JSON Body :

    [
      {
        "id": "12345",
        "eventType": "Microsoft.EventGrid/topics",
        "subject": "pubSubTest/event",
        "eventTime": "2020-03-06T21:08:02+00:00",
        "data": {
          "name": "Kam"
        },
        "dataVersion": "1.0",
        "metadataVersion": "1",
        "topic": "/subscriptions/<subscriptionID>/resourceGroups/<ResourceGroupName>/providers/Microsoft.EventGrid/topics/<EventGridTopicName>"
      }
    ]
    

    I sent the events to the Azure Event Grid Topic successfully.

    enter image description here

    Azure Function App Invocations :

    The Event Grid Trigger function was triggered successfully.

    enter image description here