您可以借助 Serverless Framework 编写 SCF 云函数来实现 Web 后端服务,并通过 API 网关对外提供服务。API 网关会将请求内容以参数形式传递给函数,并将函数返回作为响应返回给请求方。详情可以参考 API 网关触发器概述

创建 HTTP 访问的接入点

通过如下配置,可以创建一个 SCF 函数,并且创建对应的 API 网关触发器,支持 POST 请求,对应的 serverless.yml 配置如下:

  1. functions:
  2. hello_world:
  3. handler: index.main_handler
  4. runtime: Nodejs8.9
  5. events:
  6. - apigw:
  7. name: hello_world_apigw
  8. parameters:
  9. stageName: release
  10. serviceId: # if you don't specify an exsiting serviceId, a new service will be created by default.
  11. httpMethod: POST
  12. integratedResponse: true # enable integrated response

以 Node.js 为例,对应的函数代码如下:

  1. //index.js
  2. exports.main_handler = async (event, context, callback) => {
  3. console.log(event);
  4. return {
  5. isBase64Encoded: false,
  6. statusCode: 200,
  7. headers: { 'Content-Type': 'text/html' },
  8. body: 'hello world',
  9. };
  10. };

API 网关触发器的集成请求事件消息结构

在 API 网关触发器接收到请求时,会将类似以下 JSON 格式的事件数据发送给绑定的云函数。

  1. {
  2. "requestContext": {
  3. "serviceId": "service-f94sy04v",
  4. "path": "/test/{path}",
  5. "httpMethod": "POST",
  6. "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
  7. "identity": {
  8. "secretId": "abdcdxxxxxxxsdfs"
  9. },
  10. "sourceIp": "10.0.2.14",
  11. "stage": "release"
  12. },
  13. "headers": {
  14. "Accept-Language": "en-US,en,cn",
  15. "Accept": "text/html,application/xml,application/json",
  16. "Host": "service-3ei3tii4-251000691.ap-guangzhou.apigateway.myqloud.com",
  17. "User-Agent": "User Agent String"
  18. },
  19. "body": "{\"test\":\"body\"}",
  20. "pathParameters": {
  21. "path": "value"
  22. },
  23. "queryStringParameters": {
  24. "foo": "bar"
  25. },
  26. "headerParameters": {
  27. "Refer": "10.0.2.14"
  28. },
  29. "stageVariables": {
  30. "stage": "release"
  31. },
  32. "path": "/test/value",
  33. "queryString": {
  34. "foo": "bar",
  35. "bob": "alice"
  36. },
  37. "httpMethod": "POST"
  38. }