環境變數

示範如何在 Cloud Function 中使用環境變數。

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:

程式碼範例

C#

如要驗證 Cloud Run 函式,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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, context.RequestAborted);
    }
}

Go

如要驗證 Cloud Run 函式,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


// 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 Run 函式,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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 Run 函式,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

PHP

如要驗證 Cloud Run 函式,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


use Psr\Http\Message\ServerRequestInterface;

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

Python

如要驗證 Cloud Run 函式,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import os


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

Ruby

如要驗證 Cloud Run 函式,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

require "functions_framework"

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

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器