环境变量

演示如何在 Cloud Functions 函数中使用环境变量。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C#

如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Cloud.Functions.Framework;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;

namespace EnvironmentVariables;

public class Function : IHttpFunction
{
    public async Task HandleAsync(HttpContext context)
    {
        string foo = Environment.GetEnvironmentVariable("FOO")
            ?? "Specified environment variable is not set.";
        await context.Response.WriteAsync(foo);
    }
}

Go

如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// Package tips contains tips for writing Cloud Functions in Go.
package tips

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

// EnvVar is an example of getting an environment variable in a Go function.
func EnvVar(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "FOO: %q", os.Getenv("FOO"))
}

Java

如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;
import java.io.IOException;

public class EnvVars implements HttpFunction {

  // Returns the environment variable "foo" set during function deployment.
  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    BufferedWriter writer = response.getWriter();
    String foo = System.getenv("FOO");
    if (foo == null) {
      foo = "Specified environment variable is not set.";
    }
    writer.write(foo);
  }
}

Node.js

如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

exports.envVar = (req, res) => {
  // Sends 'bar' as response
  res.send(process.env.FOO);
};

PHP

如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


use Psr\Http\Message\ServerRequestInterface;

function envVar(ServerRequestInterface $request): string
{
    return getenv('FOO') . PHP_EOL;
}

Python

如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import os

def env_vars(request):
    return os.environ.get("FOO", "Specified environment variable is not set.")

Ruby

如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "functions_framework"

FunctionsFramework.http "env_vars" do |_request|
  ENV["FOO"] || "Specified environment variable is not set."
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器