在 Cloud Run 函式中,如果您想透過 HTTP(S) 要求叫用函式,就必須編寫 HTTP 函式。如要允許 HTTP 語意,請使用函式架構,並指定 HTTP 函式簽章,以便接受 HTTP 專屬引數。
實作 HTTP 處理常式函式
以下範例顯示每個執行階段的基本 HTTP 函式來源檔案。如要瞭解原始碼的位置,請參閱「來源目錄結構」。
Node.js
ES 模組
import { http } from '@google-cloud/functions-framework';
http('myHttpFunction', (req, res) => {
// Your code here
// Send an HTTP response
res.send('OK');
});
在 package.json
檔案中新增下列依附元件,包括 "type": "module"
:
{
"dependencies": {
"@google-cloud/functions-framework": "^3.0.0"
},
"type": "module"
}
CommonJS 模組
const functions = require('@google-cloud/functions-framework');
// Register an HTTP function with the Functions Framework
functions.http('myHttpFunction', (req, res) => {
// Your code here
// Send an HTTP response
res.send('OK');
});
在 package.json
檔案中新增下列依附元件:
{
"dependencies": {
"@google-cloud/functions-framework": "^3.0.0"
}
}
在 Node.js 中,您可以使用 Node.js 的 Functions Framework 註冊 HTTP 處理常式函式。HTTP 處理常式函式必須是 Express 中介函式函式,可接受 request 和 response 引數,並傳送 HTTP 回應。
Cloud Run 會使用 body-parser
根據要求的 Content-Type
標頭,自動為您剖析要求主體,讓您能夠在 HTTP 處理常式中存取 req.body
和 req.rawBody
物件。
函式進入點是處理常式向 Functions Framework 註冊時使用的名稱。在這個範例中,進入點為 myHttpFunction
。
Python
import functions_framework
# Register an HTTP function with the Functions Framework
@functions_framework.http
def my_http_function(request):
# Your code here
# Return an HTTP response
return 'OK'
在 Python 中,您可以使用 Python 專用 Functions Framework 註冊 HTTP 處理常式函式。HTTP 處理常式函式必須接受 Flask 要求物件做為引數,並傳回 Flask 可轉換為 HTTP 回應物件的值。
函式進入點是處理常式向 Functions Framework 註冊時使用的名稱。在這個範例中,進入點為 my_http_function
。
Go
package myhttpfunction
import (
"fmt"
"net/http"
"github.com/GoogleCloudPlatform/functions-framework-go/functions"
)
func init() {
// Register an HTTP function with the Functions Framework
functions.HTTP("MyHTTPFunction", myHTTPFunction)
}
// Function myHTTPFunction is an HTTP handler
func myHTTPFunction(w http.ResponseWriter, r *http.Request) {
// Your code here
// Send an HTTP response
fmt.Fprintln(w, "OK")
}
在 Go 中,您可以在 init()
函式中使用 Go 專用 Functions Framework 註冊 HTTP 處理常式函式。HTTP 處理常式函式必須使用標準 http.HandlerFunc
介面傳送 HTTP 回應。
函式進入點是處理常式向 Functions Framework 註冊時使用的名稱。在這個範例中,進入點為 MyHTTPFunction
。
HTTP 處理常式函式必須實作標準 http.HandlerFunc
介面。這個函式會接受 http.ResponseWriter 介面,該介面可讓函式建立要求的回覆,以及指向 http.Request 結構體的指標,其中包含傳入 HTTP 要求的詳細資料。
Java
package myhttpfunction;
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
// Define a class that implements the HttpFunction interface
public class MyHttpFunction implements HttpFunction {
// Implement the service() method to handle HTTP requests
@Override
public void service(HttpRequest request, HttpResponse response) throws Exception {
// Your code here
// Send an HTTP response
response.getWriter().write("OK");
}
}
在 Java 中,您可以使用 Functions Framework Java API,透過 HttpFunction
介面實作 HTTP 處理常式類別。service()
方法必須傳送 HTTP 回應。
函式進入點是 HTTP 處理常式類別的完整名稱,包括套件名稱。在這個範例中,進入點為 myhttpfunction.MyHttpFunction
。
service
方法會接收描述傳入 HTTP 要求的 HttpRequest
物件,以及函式使用回應訊息填入的 HttpResponse
物件。
.NET
using Google.Cloud.Functions.Framework;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace MyProject
{
// Define a class that implements the IHttpFunction interface
public class MyHttpFunction : IHttpFunction
{
// Implement the HandleAsync() method to handle HTTP requests
public async Task HandleAsync(HttpContext context)
{
// Your code here
// Send an HTTP response
await context.Response.WriteAsync("OK");
}
}
}
在 .NET 執行階段中,您可以使用 .NET 的函式架構,透過 IHttpFunction
介面實作 HTTP 處理常式類別。HandleAsync()
方法會接受標準 ASP.NET HttpContext
物件做為引數,且必須傳送 HTTP 回應。
函式進入點是 HTTP 處理常式類別的完整名稱,包括命名空間。在這個範例中,進入點為 MyProject.MyHttpFunction
。
Ruby
require "functions_framework"
# Register an HTTP function with the Functions Framework
FunctionsFramework.http "my_http_function" do |request|
# Your code here
# Return an HTTP response
"OK"
end
在 Ruby 中,您可以使用 Ruby 版 Functions Framework 註冊 HTTP 處理常式函式。HTTP 處理常式函式必須接受 Rack 要求物件做為引數,並傳回可用於 HTTP 回應的值。
函式進入點是處理常式向 Functions Framework 註冊時使用的名稱。在這個範例中,進入點為 my_http_function
。
PHP
<?php
use Google\CloudFunctions\FunctionsFramework;
use Psr\Http\Message\ServerRequestInterface;
// Register an HTTP function with the Functions Framework
FunctionsFramework::http('myHttpFunction', 'myHttpHandler');
// Define your HTTP handler
function myHttpHandler(ServerRequestInterface $request): string
{
// Your code here
// Return an HTTP response
return 'OK';
}
在 PHP 中,您可以使用 PHP 專用 Functions Framework 註冊 HTTP 處理常式函式。HTTP 處理常式函式必須接受實作 PSR-7 ServerRequestInterface
介面的引數,並以字串或實作 PSR-7 ResponseInterface
介面的物件傳回 HTTP 回應。
函式進入點是處理常式向 Functions Framework 註冊時使用的名稱。在這個範例中,進入點為 myHttpFunction
。
HTTP 要求和回應
使用 Functions Framework 註冊 HTTP 處理常式函式時,HTTP 處理常式可以檢查要求方法,並根據方法執行不同的動作。
當您將事件供應器設為向 Cloud Run 函式傳送 HTTP 要求時,函式就會傳送 HTTP 回應。如果函式建立背景工作 (例如使用執行緒、未來、JavaScript 承諾物件、回呼或系統程序),您必須在傳送 HTTP 回應前終止或以其他方式解決這些工作。在傳送 HTTP 回應前未終止的任何工作可能不會完成,並可能導致未定義的行為。
處理 CORs / CORS 支援
跨來源資源共享 (CORS) 可讓在一個網域中執行的應用程式存取其他網域中的資源。舉例來說,您可能需要讓網域向 Cloud Run 函式網域提出要求,才能存取函式。
如要允許跨來源要求函式,請視需要在 HTTP 回應中設定 Access-Control-Allow-Origin
標頭。對於預檢跨來源要求,您必須使用 204
回應代碼和其他標頭,回應預檢 OPTIONS
要求。
Node.js
Python
Go
Java
.NET
Ruby
PHP
如果 CORS 設定不正確,您可能會看到類似以下的錯誤:
XMLHttpRequest cannot load https://YOUR_FUNCTION_URL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://YOUR_DOMAIN' is therefore not allowed access.
CORS 限制
對於已預檢的跨來源要求,預檢 OPTIONS 要求會在沒有 Authorization 標頭的情況下傳送,因此會在所有需要驗證的 HTTP 函式中遭到拒絕。由於預檢要求失敗,因此主要要求也會失敗。如要解決這項限制,請使用下列其中一種做法:
- 允許未經驗證的叫用函式。
- 為函式設定 Identity-Aware Proxy,為傳送至 Cloud Run 函式的預檢 OPTIONS 要求提供授權標頭。
- 將網頁應用程式和 Cloud Run 託管在相同的網域中,以避免 CORS。方法是將 Firebase 託管與 Cloud Run 函式整合。