TIP

🔥 Help shape the future of Azure Tips and Tricks by telling what you'd like for us to write about here (opens new window).

💡 Learn more : Introduction to Azure Functions (opens new window).

📺 Watch the video : How to create custom handlers for Azure Functions (opens new window).

# How to create custom handlers for Azure Functions

# Run code in any language with Azure Functions

Azure Functions (opens new window) are great for running serverless pieces of code. Functions also provide triggers and bindings (opens new window), which make it easy to start a function, receive data and do something with that data, without writing plumbing code. You could already create Azure Functions in many languages, and now with Custom Handlers (opens new window), you can have a Function trigger any type of code.

Custom Handlers are lightweight web servers that receive events from the Azure Functions host. Any language that supports HTTP calls can implement a custom handler.

In this post, we'll use Custom Handlers (opens new window) to run Go code.

# Prerequisites

If you want to follow along, you'll need the following:

# Trigger Go code with an Azure Function

Let's create an Azure Function that runs code in the Go language. We'll start by creating and running a Function locally and deploy it to Azure after that.

  1. Open Visual Studio Code
  2. Go to the Azure menu. Here, you'll see the Functions section
  3. Let's create a local Azure Function. Click on the Create New Project button

(Create new local Function project in VS Code)

  1. Select a folder location to store the project and click Select
  2. This starts the creation wizard. First, select Custom Handler as the language for the project

(Select Custom Handler in VS Code)

  1. Next, select HTTP trigger for the Function template
  2. Name the local function "GoExample". This exact name is important, because we'll need it later
  3. Select Anonymous for the Authorization level
  4. Finally, select Add to workspace to create the Function

The Function will open in VS Code and is a normal, HTTP Triggered Function. Let's add a Go file to it.

  1. Right-click the explorer window and select New File in the root of the Function
  2. Name the file handler.go

(handler.go file in the root of the Function in VS Code)

  1. Paste the following Go code into the Go file. This uses the Custom Handlers feature to forward HTTP requests to the helloHandler and execute that. This way, you can execute code in whatever language you want, like Go code in this example. Make sure that the name of the function in the line "http.HandleFunc("/api/GoExample", is the same as the name of the Function
package main

 import (
 	"fmt"
 	"log"
 	"net/http"
 	"os"
 )

 func helloHandler(w http.ResponseWriter, r *http.Request) {
 	message := "This HTTP triggered function executed successfully from Go. Pass a name in the query string for a personalized response.\n"
 	name := r.URL.Query().Get("name")
 	if name != "" {
 		message = fmt.Sprintf("Hello, %s. This HTTP triggered function executed successfully from Go.\n", name)
 	}
 	fmt.Fprint(w, message)
 }

 func main() {
 	listenAddr := ":8080"
 	if val, ok := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT"); ok {
 		listenAddr = ":" + val
 	}
 	http.HandleFunc("/api/GoExample", helloHandler)
 	log.Printf("About to listen on %s. Go to https://127.0.0.1%s/", listenAddr, listenAddr)
 	log.Fatal(http.ListenAndServe(listenAddr, nil))
 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  1. Open a terminal window (Terminal > New Terminal)
  2. Type "build handler.go" and hit enter. This compiles the Go file into an executable. On Windows, this results in a file called handler.exe
  3. Now we need to change the host.json file. In it, we need to change the customHandler section to point to the handler.exe file (which can have a different name, like "handler", on Linux). The host.json file should look like this:
{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  },
  "customHandler": {
    "description": {
      "defaultExecutablePath": "handler.exe",
      "workingDirectory": "",
      "arguments": []
    },
    "enableForwardingHttpRequest": true
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  1. That's it. Let's try it out. In the terminal type func start and hit enter. This starts the Function locally and shows you the URL at which it is running
  2. Copy the URL for the Function from the output window and paste it in a browser and add "?name=Go" to the end of the URL. This is the query parameter that the Go code takes and displays

(Result of running the Function locally)

The Function works locally. The Custom Handler in Go intercepts the HTTP Trigger and invokes the Go method that executes Go code. Let's take this Function App and run it in Azure.

  1. In VS Code, go to the Azure menu
  2. If you're not logged into Azure, click Sign in to Azure and follow the instructions
  3. Click the Deploy to Function App button. This starts the deployment wizard
  4. Select "Create new Function App in Azure... Advanced"
  5. Fill in a unique Name for the Function App
  6. Select Custom Handler as the runtime stack

(Select Custom Handler as the runtime for the Azure Function App)

  1. Now pick Windows for the OS. We pick Windows, because we compiled the handler executable for Windows. If you want to run the Function on Linux:
    1. Recompile the handler.go file with "GOOS=linux GOARCH=amd64 go build handler.go"
    2. Change host.json to point to handler instead of handler.exe
  2. Pick Consumption for the hosting plan
  3. Select a Resource Group for the Function App
  4. Next, select a Storage Account for the Function App
  5. Finally, pick "Skip for now" when you are asked to select an Application Insights resource. That's it. The Function app will now be created and the code will be deployed to it
  6. When the Function App is created and the Function is deployed to Azure, refresh the Functions in VS Code
  7. Right-click on the new Function App and click Browse Website.

(Right-click the new Function App in VS Code)

  1. The Function opens in a browser. Add "/api/GoExample?name=Azure" to the end of the URL and hit enter to submit it

(Result of running the Function in Azure)

# Conclusion

You can now use Azure Functions (opens new window) to trigger code in any language with the Custom Handlers (opens new window) feature. Go and check it out!