创建通用事件处理脚本

创建一个事件处理脚本,它将传入事件作为 CloudEvent 接收。

代码示例

Go

如需向 Eventarc 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


// Sample generic is a Cloud Run service which logs and echos received requests.
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
)

// GenericHandler receives and echos a HTTP request's headers and body.
func GenericHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("Event received!")

	// Log all headers besides authorization header
	log.Println("HEADERS:")
	headerMap := make(map[string]string)
	for k, v := range r.Header {
		if k != "Authorization" {
			val := strings.Join(v, ",")
			headerMap[k] = val
			log.Println(fmt.Sprintf("%q: %q\n", k, val))
		}
	}

	// Log body
	log.Println("BODY:")
	bodyBytes, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Printf("error parsing body: %v", err)
	}
	body := string(bodyBytes)
	log.Println(body)

	// Format and print full output
	type result struct {
		Headers map[string]string `json:"headers"`
		Body    string            `json:"body"`
	}
	res := &result{
		Headers: headerMap,
		Body:    body,
	}
	if err := json.NewEncoder(w).Encode(res); err != nil {
		log.Printf("error encoding response: %v", err)
		http.Error(w, "Could not marshal JSON output", 500)
		return
	}
	fmt.Fprintln(w)
}

Java

如需向 Eventarc 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import java.util.Map;
import org.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EventController {
  @RequestMapping(value = "/", method = RequestMethod.POST)
  public ResponseEntity<String> receiveMessage(
      @RequestBody String body, @RequestHeader Map<String, String> headers) {
    System.out.println("Event received!");

    // Log headers
    System.out.println("HEADERS:");
    headers.forEach((k, v) -> {
      if (!k.equals("Authorization")) {
        System.out.printf("%s: %s\n", k, v);
      }
    });
    System.out.println("");

    // Log body
    System.out.println("BODY:");
    JSONObject jsonBody = new JSONObject(body);
    String jsonString = jsonBody.toString(2);
    System.out.println(jsonString);

    // Return headers and body
    JSONObject json = new JSONObject();
    JSONObject jsonHeaders = new JSONObject();
    json.put("headers", jsonHeaders);
    json.put("body", jsonBody);

    return new ResponseEntity<>(json.toString(), HttpStatus.OK);
  }
}

Node.js

如需向 Eventarc 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

const express = require('express');
const app = express();

app.use(express.json());
app.post('/', (req, res) => {
  console.log('Event received!');

  console.log('HEADERS:');
  delete req.headers.authorization; // do not log authorization header
  console.log(JSON.stringify(req.headers));

  console.log('BODY:');
  console.log(JSON.stringify(req.body));

  res.send({
    headers: req.headers,
    body: req.body,
  });
});

module.exports = app;

PHP

如需向 Eventarc 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

$msg = "Event received!\n";

$msg .= "\nHEADERS:\n";
$headers = getallheaders();
unset($headers['Authorization']); // do not log authorization header
foreach ($headers as $name => $value) {
    $msg .= "$name: $value\n";
}

$msg .= "\nBODY:\n";
$body = file_get_contents('php://input');
$msg .= $body . "\n";

// Write to stderr for logging
$log = fopen('php://stderr', 'wb');
fwrite($log, $msg);
// Echo to return in request body
echo $msg;

Python

如需向 Eventarc 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

@app.route("/", methods=["POST"])
def index():
    print("Event received!")

    print("HEADERS:")
    headers = dict(request.headers)
    headers.pop("Authorization", None)  # do not log authorization header if exists
    print(headers)

    print("BODY:")
    body = dict(request.json)
    print(body)

    resp = {"headers": headers, "body": body}
    return (resp, 200)

Ruby

如需向 Eventarc 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

post "/" do
  request.body.rewind # in case someone already read it

  puts "Event received!"

  puts "\nHEADERS:"
  headers = request.env.select { |k, _v| k.start_with? "HTTP_" }
                   .collect { |key, val| [key.sub(/^HTTP_/, ""), val] }
                   .collect { |key, val| "#{key}: #{val}" }
                   .sort
  headers.each do |key, value|
    if key != "Authorization"
      puts "#{key}: #{value}<br>"
    end
  end
  headers_json = headers

  puts "\nBODY:"
  body_json = JSON.parse request.body.read
  puts body_json

  result = {
    "headers" => headers_json,
    "body"    => body_json
  }
  result.to_json
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器