title | description | ms.topic | ms.date | ms.devlang | ms.custom |
---|---|---|---|---|---|
Create a function in Go or Rust using Visual Studio Code - Azure Functions |
Learn how to create a Go function as an Azure Functions custom handler, then publish the local project to serverless hosting in Azure Functions using the Azure Functions extension in Visual Studio Code. |
quickstart |
06/03/2024 |
golang |
mode-api, vscode-azure-extension-update-complete |
[!INCLUDE functions-language-selector-quickstart-vs-code]
In this article, you use Visual Studio Code to create a custom handler function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.
Custom handlers can be used to create functions in any language or runtime by running an HTTP server process. This article supports both Go and Rust.
Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.
Before you get started, make sure you have the following requirements in place:
-
An Azure account with an active subscription. Create an account for free.
-
Visual Studio Code on one of the supported platforms.
-
The Azure Functions extension for Visual Studio Code.
-
Go, latest version recommended. Use the
go version
command to check your version.
-
An Azure account with an active subscription. Create an account for free.
-
Visual Studio Code on one of the supported platforms.
-
The Azure Functions extension for Visual Studio Code.
-
Rust toolchain using rustup. Use the
rustc --version
command to check your version.
[!INCLUDE functions-install-core-tools-vs-code]
In this section, you use Visual Studio Code to create a local Azure Functions custom handlers project. Later in this article, you'll publish your function code to Azure.
-
In Visual Studio Code, press F1 to open the command palette and search for and run the command
Azure Functions: Create New Project...
. -
Choose the directory location for your project workspace and choose Select. You should either create a new folder or choose an empty folder for the project workspace. Don't choose a project folder that is already part of a workspace.
-
Provide the following information at the prompts:
Prompt Selection Select a language for your function project Choose Custom Handler
.Select a template for your project's first function Choose HTTP trigger
.Provide a function name Type HttpExample
.Authorization level Choose Anonymous
, which enables anyone to call your function endpoint. For more information, see Authorization level.Select how you would like to open your project Choose Open in current window
.Using this information, Visual Studio Code generates an Azure Functions project with an HTTP trigger. You can view the local project files in the Explorer.
The function.json file in the HttpExample folder declares an HTTP trigger function. You complete the function by adding a handler and compiling it into an executable.
-
Press Ctrl + N (Cmd + N on macOS) to create a new file. Save it as handler.go in the function app root (in the same folder as host.json).
-
In handler.go, add the following code and save the file. This is your Go custom handler.
package main import ( "fmt" "log" "net/http" "os" ) func helloHandler(w http.ResponseWriter, r *http.Request) { message := "This HTTP triggered function executed successfully. 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.\n", name) } fmt.Fprint(w, message) } func main() { listenAddr := ":8080" if val, ok := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT"); ok { listenAddr = ":" + val } http.HandleFunc("/api/HttpExample", helloHandler) log.Printf("About to listen on %s. Go to https://127.0.0.1%s/", listenAddr, listenAddr) log.Fatal(http.ListenAndServe(listenAddr, nil)) }
-
Press Ctrl + Shift + ` or select New Terminal from the Terminal menu to open a new integrated terminal in VS Code.
-
Compile your custom handler using the following command. An executable file named
handler
(handler.exe
on Windows) is output in the function app root folder.go build handler.go
-
Press Ctrl + Shift + ` or select New Terminal from the Terminal menu to open a new integrated terminal in VS Code.
-
In the function app root (the same folder as host.json), initialize a Rust project named
handler
.cargo init --name handler
-
In Cargo.toml, add the following dependencies necessary to complete this quickstart. The example uses the warp web server framework.
[dependencies] warp = "0.3" tokio = { version = "1", features = ["rt", "macros", "rt-multi-thread"] }
-
In src/main.rs, add the following code and save the file. This is your Rust custom handler.
use std::collections::HashMap; use std::env; use std::net::Ipv4Addr; use warp::{http::Response, Filter}; #[tokio::main] async fn main() { let example1 = warp::get() .and(warp::path("api")) .and(warp::path("HttpExample")) .and(warp::query::<HashMap<String, String>>()) .map(|p: HashMap<String, String>| match p.get("name") { Some(name) => Response::builder().body(format!("Hello, {}. This HTTP triggered function executed successfully.", name)), None => Response::builder().body(String::from("This HTTP triggered function executed successfully. Pass a name in the query string for a personalized response.")), }); let port_key = "FUNCTIONS_CUSTOMHANDLER_PORT"; let port: u16 = match env::var(port_key) { Ok(val) => val.parse().expect("Custom Handler port is not a number!"), Err(_) => 3000, }; warp::serve(example1).run((Ipv4Addr::LOCALHOST, port)).await }
-
Compile a binary for your custom handler. An executable file named
handler
(handler.exe
on Windows) is output in the function app root folder.cargo build --release cp target/release/handler .
The function host needs to be configured to run your custom handler binary when it starts.
-
Open host.json.
-
In the
customHandler.description
section, set the value ofdefaultExecutablePath
tohandler
(on Windows, set it tohandler.exe
). -
In the
customHandler
section, add a property namedenableForwardingHttpRequest
and set its value totrue
. For functions consisting of only an HTTP trigger, this setting simplifies programming by allow you to work with a typical HTTP request instead of the custom handler request payload. -
Confirm the
customHandler
section looks like this example. Save the file."customHandler": { "description": { "defaultExecutablePath": "handler", "workingDirectory": "", "arguments": [] }, "enableForwardingHttpRequest": true }
The function app is configured to start your custom handler executable.
You can run this project on your local development computer before you publish to Azure.
-
In the integrated terminal, start the function app using Azure Functions Core Tools.
func start
-
With Core Tools running, navigate to the following URL to execute a GET request, which includes
?name=Functions
query string.http://localhost:7071/api/HttpExample?name=Functions
-
A response is returned, which looks like the following in a browser:
-
Information about the request is shown in Terminal panel.
-
Press Ctrl + C to stop Core Tools.
After you've verified that the function runs correctly on your local computer, it's time to use Visual Studio Code to publish the project directly to Azure.
[!INCLUDE functions-sign-in-vs-code]
In this section, you publish your project to Azure in a function app running Linux. In most cases, you must recompile your binary and adjust your configuration to match the target platform before publishing it to Azure.
-
In the integrated terminal, compile the handler to Linux/x64. A binary named
handler
is created in the function app root.GOOS=linux GOARCH=amd64 go build handler.go
GOOS=linux GOARCH=amd64 go build handler.go
set GOOS=linux set GOARCH=amd64 go build handler.go
Change the
defaultExecutablePath
in host.json fromhandler.exe
tohandler
. This instructs the function app to run the Linux binary.
-
Create a file at .cargo/config. Add the following contents and save the file.
[target.x86_64-unknown-linux-musl] linker = "rust-lld"
-
In the integrated terminal, compile the handler to Linux/x64. A binary named
handler
is created. Copy it to the function app root.rustup target add x86_64-unknown-linux-musl cargo build --release --target=x86_64-unknown-linux-musl cp target/x86_64-unknown-linux-musl/release/handler .
-
If you are using Windows, change the
defaultExecutablePath
in host.json fromhandler.exe
tohandler
. This instructs the function app to run the Linux binary. -
Add the following line to the .funcignore file:
target
This prevents publishing the contents of the target folder.
In this section, you create a function app and related resources in your Azure subscription.
-
Choose the Azure icon in the Activity bar. Then in the Resources area, select the + icon and choose the Create Function App in Azure option.
-
Provide the following information at the prompts:
Prompt Selection Select subscription Choose the subscription to use. You won't see this when you have only one subscription visible under Resources. Enter a globally unique name for the function app Type a name that is valid in a URL path. The name you type is validated to make sure that it's unique in Azure Functions. Select a runtime stack Choose Custom Handler. Select a location for new resources For better performance, choose a region near you. The extension shows the status of individual resources as they are being created in Azure in the Azure: Activity Log panel.
-
When the creation is complete, the following Azure resources are created in your subscription. The resources are named based on your function app name:
[!INCLUDE functions-vs-code-created-resources]
A notification is displayed after your function app is created and the deployment package is applied.
[!INCLUDE functions-vs-code-create-tip]
[!INCLUDE functions-deploy-project-vs-code]
[!INCLUDE functions-vs-code-run-remote]
[!INCLUDE functions-cleanup-resources-vs-code.md]
[!div class="nextstepaction"] Learn about Azure Functions custom handlers