HTTP 함수가 'Hello, world!'로 응답합니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
- Go를 사용하여 HTTP Cloud 함수 만들기 및 배포
- Node.js를 사용하여 HTTP Cloud 함수 만들기 및 배포
- PHP를 사용하여 HTTP Cloud 함수 만들기 및 배포
- Python을 사용하여 HTTP Cloud 함수 만들기 및 배포
- Ruby를 사용하여 HTTP Cloud 함수 만들기 및 배포
- Node.js의 종속 항목 지정
- HTTP 함수 테스트
- 도움말 및 유용한 정보
코드 샘플
C#
using Google.Cloud.Functions.Framework;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
namespace HelloHttp;
public class Function : IHttpFunction
{
private readonly ILogger _logger;
public Function(ILogger<Function> logger) =>
_logger = logger;
public async Task HandleAsync(HttpContext context)
{
HttpRequest request = context.Request;
// Check URL parameters for "name" field
// "world" is the default value
string name = ((string) request.Query["name"]) ?? "world";
// If there's a body, parse it as JSON and check for "name" field.
using TextReader reader = new StreamReader(request.Body);
string text = await reader.ReadToEndAsync();
if (text.Length > 0)
{
try
{
JsonElement json = JsonSerializer.Deserialize<JsonElement>(text);
if (json.TryGetProperty("name", out JsonElement nameElement) &&
nameElement.ValueKind == JsonValueKind.String)
{
name = nameElement.GetString();
}
}
catch (JsonException parseException)
{
_logger.LogError(parseException, "Error parsing JSON request");
}
}
await context.Response.WriteAsync($"Hello {name}!");
}
}
Go
// Package helloworld provides a set of Cloud Functions samples.
package helloworld
import (
"encoding/json"
"fmt"
"html"
"net/http"
"github.com/GoogleCloudPlatform/functions-framework-go/functions"
)
func init() {
functions.HTTP("HelloHTTP", HelloHTTP)
}
// HelloHTTP is an HTTP Cloud Function with a request parameter.
func HelloHTTP(w http.ResponseWriter, r *http.Request) {
var d struct {
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
fmt.Fprint(w, "Hello, World!")
return
}
if d.Name == "" {
fmt.Fprint(w, "Hello, World!")
return
}
fmt.Fprintf(w, "Hello, %s!", html.EscapeString(d.Name))
}
Java
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;
public class HelloHttp implements HttpFunction {
private static final Logger logger = Logger.getLogger(HelloHttp.class.getName());
private static final Gson gson = new Gson();
@Override
public void service(HttpRequest request, HttpResponse response)
throws IOException {
// Check URL parameters for "name" field
// "world" is the default value
String name = request.getFirstQueryParameter("name").orElse("world");
// Parse JSON request and check for "name" field
try {
JsonElement requestParsed = gson.fromJson(request.getReader(), JsonElement.class);
JsonObject requestJson = null;
if (requestParsed != null && requestParsed.isJsonObject()) {
requestJson = requestParsed.getAsJsonObject();
}
if (requestJson != null && requestJson.has("name")) {
name = requestJson.get("name").getAsString();
}
} catch (JsonParseException e) {
logger.severe("Error parsing JSON: " + e.getMessage());
}
var writer = new PrintWriter(response.getWriter());
writer.printf("Hello %s!", name);
}
}
Node.js
const functions = require('@google-cloud/functions-framework');
const escapeHtml = require('escape-html');
/**
* Responds to an HTTP request using data from the request body parsed according
* to the "content-type" header.
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
functions.http('helloHttp', (req, res) => {
res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);
});
PHP
<?php
use Google\CloudFunctions\FunctionsFramework;
use Psr\Http\Message\ServerRequestInterface;
// Register the function with Functions Framework.
// This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=http` environment
// variable when deploying. The `FUNCTION_TARGET` environment variable should
// match the first parameter.
FunctionsFramework::http('helloHttp', 'helloHttp');
function helloHttp(ServerRequestInterface $request): string
{
$name = 'World';
$body = $request->getBody()->getContents();
if (!empty($body)) {
$json = json_decode($body, true);
if (json_last_error() != JSON_ERROR_NONE) {
throw new RuntimeException(sprintf(
'Could not parse body: %s',
json_last_error_msg()
));
}
$name = $json['name'] ?? $name;
}
$queryString = $request->getQueryParams();
$name = $queryString['name'] ?? $name;
return sprintf('Hello, %s!', htmlspecialchars($name));
}
Python
from flask import escape
import functions_framework
@functions_framework.http
def hello_http(request):
"""HTTP Cloud Function.
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>.
"""
request_json = request.get_json(silent=True)
request_args = request.args
if request_json and 'name' in request_json:
name = request_json['name']
elif request_args and 'name' in request_args:
name = request_args['name']
else:
name = 'World'
return 'Hello {}!'.format(escape(name))
Ruby
require "functions_framework"
require "cgi"
require "json"
FunctionsFramework.http "hello_http" do |request|
# The request parameter is a Rack::Request object.
# See https://www.rubydoc.info/gems/rack/Rack/Request
name = request.params["name"] ||
(JSON.parse(request.body.read)["name"] rescue nil) ||
"World"
# Return the response body as a string.
# You can also return a Rack::Response object, a Rack response array, or
# a hash which will be JSON-encoded into a response.
"Hello #{CGI.escape_html name}!"
end
다음 단계
다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.