Jenis metode HTTP
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Menunjukkan cara menangani jenis metode HTTP (seperti GET, PUT, dan POST) di Cloud Functions.
Contoh kode
Kecuali dinyatakan lain, konten di halaman ini dilisensikan berdasarkan Lisensi Creative Commons Attribution 4.0, sedangkan contoh kode dilisensikan berdasarkan Lisensi Apache 2.0. Untuk mengetahui informasi selengkapnya, lihat Kebijakan Situs Google Developers. Java adalah merek dagang terdaftar dari Oracle dan/atau afiliasinya.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis content demonstrates how to handle different HTTP method types within Cloud Functions, including GET, PUT, and handling unsupported methods.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples provided show how to differentiate responses based on the HTTP method used in the request.\u003c/p\u003e\n"],["\u003cp\u003eFor GET requests, the functions respond with a "Hello World!" message and an HTTP status of 200 (OK).\u003c/p\u003e\n"],["\u003cp\u003eFor PUT requests, the functions return a "Forbidden!" message along with an HTTP status of 403 (Forbidden).\u003c/p\u003e\n"],["\u003cp\u003eAny HTTP method that is not GET or PUT results in an HTTP status of 405 (Method Not Allowed) and an error message.\u003c/p\u003e\n"]]],[],null,["# HTTP method types\n\nShows how to handle HTTP method types (such as GET, PUT, and POST) in Cloud Functions.\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n using Google.Cloud.Functions.Framework;\n using Microsoft.AspNetCore.Http;\n using System.Net;\n using System.Threading.Tasks;\n\n namespace HttpRequestMethod;\n\n public class Function : IHttpFunction\n {\n public async Task HandleAsync(HttpContext context)\n {\n HttpResponse response = context.Response;\n switch (context.Request.Method)\n {\n case \"GET\":\n response.StatusCode = (int) HttpStatusCode.OK;\n await response.WriteAsync(\"Hello world!\", context.RequestAborted);\n break;\n case \"PUT\":\n response.StatusCode = (int) HttpStatusCode.Forbidden;\n await response.WriteAsync(\"Forbidden!\", context.RequestAborted);\n break;\n default:\n response.StatusCode = (int) HttpStatusCode.MethodNotAllowed;\n await response.WriteAsync(\"Something blew up!\", context.RequestAborted);\n break;\n }\n }\n }\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package http provides a set of HTTP Cloud Functions samples.\n package http\n\n import (\n \t\"fmt\"\n \t\"net/http\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n func init() {\n \t// Register an HTTP function with the Functions Framework\n \tfunctions.HTTP(\"HelloHTTPMethod\", HelloHTTPMethod)\n }\n\n // HelloHTTPMethod is an HTTP Cloud function.\n // It uses the request method to differentiate the response.\n func HelloHTTPMethod(w http.ResponseWriter, r *http.Request) {\n \tswitch r.Method {\n \tcase http.MethodGet:\n \t\tfmt.Fprint(w, \"Hello World!\")\n \tcase http.MethodPut:\n \t\thttp.Error(w, \"403 - Forbidden\", http.StatusForbidden)\n \tdefault:\n \t\thttp.Error(w, \"405 - Method Not Allowed\", http.StatusMethodNotAllowed)\n \t}\n }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import java.io.BufferedWriter;\n import java.io.IOException;\n import java.net.HttpURLConnection;\n\n public class HttpMethod implements HttpFunction {\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException {\n\n BufferedWriter writer = response.getWriter();\n\n switch (request.getMethod()) {\n case \"GET\":\n response.setStatusCode(HttpURLConnection.HTTP_OK);\n writer.write(\"Hello world!\");\n break;\n case \"PUT\":\n response.setStatusCode(HttpURLConnection.HTTP_FORBIDDEN);\n writer.write(\"Forbidden!\");\n break;\n default:\n response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);\n writer.write(\"Something blew up!\");\n break;\n }\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const functions = require('@google-cloud/functions-framework');\n\n /**\n * Responds to a GET request with \"Hello World!\". Forbids a PUT request.\n *\n * @example\n * gcloud functions call helloHttp\n *\n * @param {Object} req Cloud Function request context.\n * @param {Object} res Cloud Function response context.\n */\n functions.http('helloHttp', (req, res) =\u003e {\n switch (req.method) {\n case 'GET':\n res.status(200).send('Hello World!');\n break;\n case 'PUT':\n res.status(403).send('Forbidden!');\n break;\n default:\n res.status(405).send({error: 'Something blew up!'});\n break;\n }\n });\n\n### PHP\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n use Psr\\Http\\Message\\ResponseInterface;\n use Psr\\Http\\Message\\ServerRequestInterface;\n use GuzzleHttp\\Psr7\\Response;\n\n function httpMethod(ServerRequestInterface $request): ResponseInterface\n {\n switch ($request-\u003egetMethod()) {\n case 'GET':\n // Example: read request\n return new Response(\n 200, // OK\n [],\n 'Hello, World!' . PHP_EOL\n );\n break;\n case 'PUT':\n // Example: write request to a read-only resource\n return new Response(\n 403, // Permission denied\n [],\n 'Forbidden!' . PHP_EOL\n );\n break;\n default:\n // Example: request type not supported by the application\n $json_payload = json_encode([\n 'error' =\u003e 'something blew up!'\n ]);\n return new Response(\n 405, // Method not allowed\n ['Content-Type' =\u003e 'application/json'],\n $json_payload\n );\n break;\n }\n }\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import functions_framework\n\n @functions_framework.http\n def hello_method(request):\n \"\"\"Responds to a GET request with \"Hello world!\". Forbids a PUT request.\n Args:\n request (flask.Request): The request object.\n \u003chttps://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data\u003e\n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_response`\n \u003chttps://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response\u003e.\n \"\"\"\n from flask import abort\n\n if request.method == \"GET\":\n return \"Hello World!\"\n elif request.method == \"PUT\":\n return abort(403)\n else:\n return abort(405)\n\n### Ruby\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n require \"functions_framework\"\n require \"json\"\n\n FunctionsFramework.http \"http_method\" do |request|\n # The request parameter is a Rack::Request object.\n # See https://www.rubydoc.info/gems/rack/Rack/Request\n case request.request_method\n when \"GET\"\n status = 200\n body = \"Hello World!\"\n when \"PUT\"\n status = 403\n body = \"Forbidden!\"\n else\n status = 405\n body = '{\"error\":\"Something blew up!\"}'\n end\n\n # Return the response body as a Rack::Response object.\n ::Rack::Response.new body, status\n end\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]