快速入门:在 Azure 中使用 Visual Studio Code 创建 Go 或 Rust 函数Quickstart: Create a Go or Rust function in Azure using Visual Studio Code

在本文中,你将使用 Visual Studio Code 来创建一个响应 HTTP 请求的自定义处理程序函数。In this article, you use Visual Studio Code to create a custom handler function that responds to HTTP requests. 在本地测试代码后,将代码部署到 Azure Functions 的无服务器环境。After testing the code locally, you deploy it to the serverless environment of Azure Functions.

可以使用自定义处理程序,通过运行 HTTP 服务器进程以任意语言或运行时创建函数。Custom handlers can be used to create functions in any language or runtime by running an HTTP server process. 本文支持 GoRustThis article supports both Go and Rust.

完成本快速入门会从你的 Azure 帐户中扣取最多几美分的费用。Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

配置环境Configure your environment

在开始之前,请确保已满足下列要求:Before you get started, make sure you have the following requirements in place:

创建本地项目Create your local project

在本部分,你将使用 Visual Studio Code 创建一个本地 Azure Functions 自定义处理程序项目。In this section, you use Visual Studio Code to create a local Azure Functions custom handlers project. 稍后在本文中,你要将函数代码发布到 Azure。Later in this article, you'll publish your function code to Azure.

  1. 在活动栏中选择“Azure”图标,然后在“Azure:函数”区域中选择“创建新项目...”图标。Choose the Azure icon in the Activity bar, then in the Azure: Functions area, select the Create new project... icon.

    选择“创建新项目”

  2. 为项目工作区选择目录位置,然后选择“选择” 。Choose a directory location for your project workspace and choose Select.

    备注

    这些步骤已设计为在工作区之外完成。These steps were designed to be completed outside of a workspace. 在这种情况下,请不要选择属于工作区内的项目文件夹。In this case, do not select a project folder that is part of a workspace.

  3. 根据提示提供以下信息:Provide the following information at the prompts:

    • 选择函数项目的语言:选择CustomSelect a language for your function project: Choose Custom.

    • 为项目的第一个函数选择模板:选择HTTP triggerSelect a template for your project's first function: Choose HTTP trigger.

    • 提供函数名称:键入 HttpExampleProvide a function name: Type HttpExample.

    • 授权级别:选择 Anonymous,这使任何人都可以调用你的函数终结点。Authorization level: Choose Anonymous, which enables anyone to call your function endpoint. 若要了解授权级别,请参阅授权密钥To learn about authorization level, see Authorization keys.

    • 选择打开项目的方式:选择Add to workspaceSelect how you would like to open your project: Choose Add to workspace.

  4. Visual Studio Code 将使用此信息生成一个包含 HTTP 触发器函数的 Azure Functions 项目。Using this information, Visual Studio Code generates an Azure Functions project with an HTTP trigger function. 可以在资源管理器中查看本地项目文件。You can view the local project files in the Explorer. 若要详细了解所创建的文件,请参阅生成的项目文件To learn more about files that are created, see Generated project files.

创建和生成函数Create and build your function

HttpExample 文件夹中的 function.json 文件声明 HTTP 触发器函数 。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.

  1. Ctrl + N(对于 macOS,则为 Cmd + N)新建文件。Press Ctrl + N (Cmd + N on macOS) to create a new file. 在函数应用根文件夹(host.json 所在的文件夹)中将其另存为 handler.go 。Save it as handler.go in the function app root (in the same folder as host.json).

  2. 在 handler.go 中,添加以下代码并保存文件。In handler.go, add the following code and save the file. 这就是 Go 自定义处理程序。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))
    }
    
  3. Ctrl + Shift +` 或在“终端”菜单中选择“新建终端”,在 VS Code 中打开新的集成终端 。Press Ctrl + Shift + ` or select New Terminal from the Terminal menu to open a new integrated terminal in VS Code.

  4. 使用以下命令编译自定义处理程序。Compile your custom handler using the following command. 函数应用的根文件夹中会输出名为 handler(对于 Windows,则为 handler.exe)的可执行文件。An executable file named handler (handler.exe on Windows) is output in the function app root folder.

    go build handler.go
    

    VS Code - 生成 Go 自定义处理程序

配置函数应用Configure your function app

函数主机需配置为在启动时运行自定义处理程序二进制文件。The function host needs to be configured to run your custom handler binary when it starts.

  1. 打开 host.json。Open host.json.

  2. customHandler.description 部分中,将 defaultExecutablePath 的值设置为 handler(对于 Windows,则将其设置为 handler.exe)。In the customHandler.description section, set the value of defaultExecutablePath to handler (on Windows, set it to handler.exe).

  3. customHandler 部分中,添加名为 enableForwardingHttpRequest 的属性并将其值设置为 trueIn the customHandler section, add a property named enableForwardingHttpRequest and set its value to true. 对于仅包含 HTTP 触发器的函数,通过此设置可处理典型的 HTTP 请求(而不是自定义处理程序请求有效负载),从而简化编程。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.

  4. 确认 customHandler 部分是否如以下示例所示。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.

在本地运行函数Run the function locally

可以先在本地开发计算机上运行此项目,然后再将其发布到 Azure。You can run this project on your local development computer before you publish to Azure.

  1. 在集成终端中,使用 Azure Functions Core Tools 启动函数应用。In the integrated terminal, start the function app using Azure Functions Core Tools.

    func start
    
  2. 在 Core Tools 运行时,导航至以下 URL 以执行 GET 请求(其中包括 ?name=Functions 查询字符串)。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

  3. 系统会返回响应,在浏览器中如下所示:A response is returned, which looks like the following in a browser:

    浏览器 - localhost 示例输出

  4. 有关请求的信息将显示在“终端” 面板中。Information about the request is shown in Terminal panel.

    任务主机启动 - VS Code 终端输出

  5. Ctrl + C 停止 Core Tools。Press Ctrl + C to stop Core Tools.

确认该函数可以在本地计算机上正确运行以后,可以使用 Visual Studio Code 将项目直接发布到 Azure。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.

登录 AzureSign in to Azure

在发布应用之前,必须先登录到 Azure。Before you can publish your app, you must sign in to Azure.

  1. 打开 Visual Studio Code,然后单击 View -> Command Palette...Open Visual Studio Code, click View -> Command Palette....

  2. 输入 Sign In to Azure Cloud,以搜索 Azure 中国环境。Input Sign In to Azure Cloud to search Azure China Environment.

  3. 在搜索结果中单击 Azure ChinaClick Azure China in search result.

  4. 窗口的右下角将出现一个弹出窗口。You will find a popup window at the bottom right of your window.

    弹出窗口

  5. 打开页面 **https://microsoft.com/deviceloginchina**,然后输入该代码进行身份验证。Open the page https://microsoft.com/deviceloginchina and enter the code to authenticate.

编译 Azure 的自定义处理程序Compile the custom handler for Azure

在本部分,你将在运行 Linux 的函数应用中将项目发布到 Azure。In this section, you publish your project to Azure in a function app running Linux. 在大多数情况下,必须先重新编译二进制文件并将配置调整为与目标平台匹配,然后才可将其发布到 Azure。In most cases, you must recompile your binary and adjust your configuration to match the target platform before publishing it to Azure.

  1. 在集成终端中,将处理程序编译为 Linux/x64。In the integrated terminal, compile the handler to Linux/x64. 函数应用根文件夹中会创建名为 handler 的二进制文件。A binary named handler is created in the function app root.

    GOOS=linux GOARCH=amd64 go build handler.go
    

将项目发布到 AzurePublish the project to Azure

在本部分,你将在 Azure 订阅中创建一个函数应用和相关资源,然后部署代码。In this section, you create a function app and related resources in your Azure subscription and then deploy your code.

重要

发布到现有函数应用将覆盖该应用在 Azure 中的内容。Publishing to an existing function app overwrites the content of that app in Azure.

  1. 在活动栏中选择“Azure”图标,然后在“Azure:函数”区域中,选择“部署到函数应用...”按钮。Choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose the Deploy to function app... button.

    将项目发布到 Azure

  2. 根据提示提供以下信息:Provide the following information at the prompts:

    • 选择文件夹:从工作区中选择一个文件夹,或浏览到包含函数应用的文件夹。Select folder: Choose a folder from your workspace or browse to one that contains your function app. 如果已打开有效的函数应用,则不会看到此信息。You won't see this if you already have a valid function app opened.

    • 选择订阅:选择要使用的订阅。Select subscription: Choose the subscription to use. 如果只有一个订阅,则不会看到此项。You won't see this if you only have one subscription.

    • 在 Azure 中选择函数应用:选择+ Create new Function App (advanced)Select Function App in Azure: Choose + Create new Function App (advanced).

      重要

      使用 advanced 选项,可选择在 Azure 中运行函数应用的特定操作系统,在本例中为 Linux。The advanced option lets you choose the specific operating system on which your function app runs in Azure, which in this case is Linux.

      VS Code - 选择“高级”新建函数应用

    • 输入函数应用的全局唯一名称:键入在 URL 路径中有效的名称。Enter a globally unique name for the function app: Type a name that is valid in a URL path. 将对你键入的名称进行验证,以确保其在 Azure Functions 中是唯一的。The name you type is validated to make sure that it's unique in Azure Functions.

    • 选择运行时堆栈:选择Custom HandlerSelect a runtime stack: Choose Custom Handler.

    • 选择 OS:选择LinuxSelect an OS: Choose Linux.

    • 选择托管计划:选择ConsumptionSelect a hosting plan: Choose Consumption.

    • 选择资源组:选择+ Create new resource groupSelect a resource group: Choose + Create new resource group. 输入资源组的名称。Enter a name for the resource group. 此名称必须在 Azure 订阅中具有唯一性。This name must be unique within your Azure subscription. 可以使用提示中推荐的名称。You can use the name suggested in the prompt.

    • 选择存储帐户:选择+ Create new storage accountSelect a storage account: Choose + Create new storage account. 该名称在 Azure 中必须全局唯一。This name must be globally unique within Azure. 可以使用提示中推荐的名称。You can use the name suggested in the prompt.

    • 选择 Application Insights 资源:选择+ Create Application Insights resourceSelect an Application Insights resource: Choose + Create Application Insights resource. 该名称在 Azure 中必须全局唯一。This name must be globally unique within Azure. 可以使用提示中推荐的名称。You can use the name suggested in the prompt.

    • 选择新资源的位置:为了提高性能,请选择你附近的 区域。在 Azure 中创建单个资源时,扩展会在通知区域显示这些资源的状态。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 notification area.

    Azure 资源创建通知

  3. 完成后,将在订阅中创建以下 Azure 资源:When completed, the following Azure resources are created in your subscription:

    • 一个资源组:相关资源的逻辑容器。A resource group, which is a logical container for related resources.
    • 一个标准 Azure 存储帐户:用于维护项目的状态和其他信息。A standard Azure Storage account, which maintains state and other information about your projects.
    • 一个消耗计划:用于定义无服务器函数应用的基础主机。A consumption plan, which defines the underlying host for your serverless function app.
    • 一个函数应用:提供用于执行函数代码的环境。A function app, which provides the environment for executing your function code. 可以通过函数应用将函数分组为逻辑单元,以便在同一托管计划中更轻松地管理、部署和共享资源。A function app lets you group functions as a logical unit for easier management, deployment, and sharing of resources within the same hosting plan.
    • 一个连接到函数应用的 Application Insights 实例:用于跟踪无服务器函数的使用情况。An Application Insights instance connected to the function app, which tracks usage of your serverless function.

    创建函数应用并应用了部署包之后,会显示一个通知。A notification is displayed after your function app is created and the deployment package is applied.

  4. 在此通知中选择“查看输出”以查看创建和部署结果,其中包括你创建的 Azure 资源。Select View Output in this notification to view the creation and deployment results, including the Azure resources that you created. 如果错过了通知,请选择右下角的响铃图标以再次查看。If you miss the notification, select the bell icon in the lower right corner to see it again.

    创建完成通知

在 Azure 中运行函数Run the function in Azure

  1. 返回到“Azure:函数”区域(位于侧栏中),然后展开你的订阅、新的函数应用和“函数”。Back in the Azure: Functions area in the side bar, expand your subscription, your new function app, and Functions. 右键单击 (Windows) 或按 Ctrl - 单击 (macOS) HttpExample 函数,然后选择“立即执行函数...”。Right-click (Windows) or Ctrl - click (macOS) the HttpExample function and choose Execute Function Now....

    立即在 Azure 的 Visual Studio Code 中执行函数

  2. 在“输入请求正文”中,你将看到请求消息正文值 { "name": "Azure" }In Enter request body you see the request message body value of { "name": "Azure" }. 按 Enter 将此请求消息发送给函数。Press Enter to send this request message to your function.

  3. 当函数在 Azure 中执行并返回响应时,Visual Studio Code 中将引发通知。When the function executes in Azure and returns a response, a notification is raised in Visual Studio Code.

清理资源Clean up resources

若要继续执行下一步骤将 Azure 存储队列绑定添加到函数,需要保留到目前为止构建的所有资源。When you continue to the next step and add an Azure Storage queue binding to your function, you'll need to keep all your resources in place to build on what you've already done.

否则,可以使用以下步骤删除函数应用及其相关资源,以免产生任何额外的费用。Otherwise, you can use the following steps to delete the function app and its related resources to avoid incurring any further costs.

  1. 在 Visual Studio Code 中,按 F1 打开命令面板In Visual Studio Code, press F1 to open the command palette. 在命令面板中,搜索并选择 Azure Functions: Open in portalIn the command palette, search for and select Azure Functions: Open in portal.

  2. 选择你的函数应用,然后按 EnterChoose your function app, and press Enter. 随即将在 Azure 门户中打开函数应用页面。The function app page opens in the Azure portal.

  3. 在“概览”选项卡中,选择“资源组”旁边的命名链接。In the Overview tab, select the named link next to Resource group.

    从函数应用页选择要删除的资源组。

  4. 在“资源组”页中查看所包括的资源的列表,然后验证这些资源是否是要删除的。In the Resource group page, review the list of included resources, and verify that they are the ones you want to delete.

  5. 选择“删除资源组”,然后按说明操作。Select Delete resource group, and follow the instructions.

    可能需要数分钟才能删除完毕。Deletion may take a couple of minutes. 完成后会显示一个通知,持续数秒。When it's done, a notification appears for a few seconds. 也可以选择页面顶部的钟形图标来查看通知。You can also select the bell icon at the top of the page to view the notification.

若要详细了解 Functions 的费用,请参阅估算消耗计划成本To learn more about Functions costs, see Estimating Consumption plan costs.

后续步骤Next steps