HTTP メソッドの種類

Cloud Functions で HTTP メソッドの種類(GET、PUT、POST など)を処理する方法を示します。

このコードサンプルが含まれるドキュメント ページ

コンテキストで使用されているコードサンプルを見るには、次のドキュメントをご覧ください。

コードサンプル

C#

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

namespace HttpRequestMethod
{
    public class Function : IHttpFunction
    {
        public async Task HandleAsync(HttpContext context)
        {
            HttpResponse response = context.Response;
            switch (context.Request.Method)
            {
                case "GET":
                    response.StatusCode = (int) HttpStatusCode.OK;
                    await response.WriteAsync("Hello world!");
                    break;
                case "PUT":
                    response.StatusCode = (int) HttpStatusCode.Forbidden;
                    await response.WriteAsync("Forbidden!");
                    break;
                default:
                    response.StatusCode = (int) HttpStatusCode.MethodNotAllowed;
                    await response.WriteAsync("Something blew up!");
                    break;
            }
        }
    }
}

C++

#include <google/cloud/functions/http_request.h>
#include <google/cloud/functions/http_response.h>

namespace gcf = ::google::cloud::functions;

gcf::HttpResponse http_method(gcf::HttpRequest request) {  // NOLINT
  if (request.verb() == "GET") {
    return gcf::HttpResponse{}
        .set_header("content-type", "text/plain")
        .set_payload("Hello World!");
  }

  return gcf::HttpResponse{}.set_result(
      request.verb() == "POST" ? gcf::HttpResponse::kForbidden
                               : gcf::HttpResponse::kMethodNotAllowed);
}

Go


// Package http provides a set of HTTP Cloud Functions samples.
package http

import (
	"fmt"
	"net/http"
)

// HelloHTTPMethod is an HTTP Cloud function.
// It uses the request method to differentiate the response.
func HelloHTTPMethod(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		fmt.Fprint(w, "Hello World!")
	case http.MethodPut:
		http.Error(w, "403 - Forbidden", http.StatusForbidden)
	default:
		http.Error(w, "405 - Method Not Allowed", http.StatusMethodNotAllowed)
	}
}

Java


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;
import java.net.HttpURLConnection;

public class HttpMethod implements HttpFunction {
  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {

    BufferedWriter writer = response.getWriter();

    switch (request.getMethod()) {
      case "GET":
        response.setStatusCode(HttpURLConnection.HTTP_OK);
        writer.write("Hello world!");
        break;
      case "PUT":
        response.setStatusCode(HttpURLConnection.HTTP_FORBIDDEN);
        writer.write("Forbidden!");
        break;
      default:
        response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);
        writer.write("Something blew up!");
        break;
    }
  }
}

Node.js

/**
 * Responds to a GET request with "Hello World!". Forbids a PUT request.
 *
 * @example
 * gcloud functions call helloHttp
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
exports.helloHttp = (req, res) => {
  switch (req.method) {
    case 'GET':
      res.status(200).send('Hello World!');
      break;
    case 'PUT':
      res.status(403).send('Forbidden!');
      break;
    default:
      res.status(405).send({error: 'Something blew up!'});
      break;
  }
};

PHP


use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use GuzzleHttp\Psr7\Response;

function httpMethod(ServerRequestInterface $request): ResponseInterface
{
    switch ($request->getMethod()) {
        case 'GET':
            // Example: read request
            return new Response(
                200, // OK
                [],
                'Hello, World!' . PHP_EOL
            );
            break;
        case 'PUT':
            // Example: write request to a read-only resource
            return new Response(
                403, // Permission denied
                [],
                'Forbidden!' . PHP_EOL
            );
            break;
        default:
            // Example: request type not supported by the application
            $json_payload = json_encode([
                'error' => 'something blew up!'
            ]);
            return new Response(
                405, // Method not allowed
                ['Content-Type' => 'application/json'],
                $json_payload
            );
            break;
    }
}

Python

def hello_method(request):
    """ Responds to a GET request with "Hello world!". Forbids a PUT request.
    Args:
        request (flask.Request): The request object.
        <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
    """
    from flask import abort

    if request.method == 'GET':
        return 'Hello World!'
    elif request.method == 'PUT':
        return abort(403)
    else:
        return abort(405)

Ruby

require "functions_framework"
require "json"

FunctionsFramework.http "http_method" do |request|
  # The request parameter is a Rack::Request object.
  # See https://www.rubydoc.info/gems/rack/Rack/Request
  case request.request_method
  when "GET"
    status = 200
    body = "Hello World!"
  when "PUT"
    status = 403
    body = "Forbidden!"
  else
    status = 405
    body = '{"error":"Something blew up!"}'
  end

  # Return the response body as a Rack::Response object.
  ::Rack::Response.new body, status
end

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。