全部产品

2. 编写函数代码

更新时间:2018-09-01 13:09:36

函数创建成功后,进入新创建的函数,根据所选的开发语言粘贴示例代码到控制台的代码编辑处。

如果您使用 Python 或 Nodejs,您可以直接在代码编辑处编写代码。如果您使用 Java,您需要将代码和依赖包共同打成 jar 包,上传至函数计算。

函数代码

Nodejs

  1. module.exports.handler = function(event, context, callback) {
  2. var event = JSON.parse(event);
  3. var content = {
  4. path: event.path,
  5. method: event.method,
  6. headers: event.headers,
  7. queryParameters: event.queryParameters,
  8. pathParameters: event.pathParameters,
  9. body: event.body
  10. // you can deal with your own logic here.
  11. }
  12. var response = {
  13. isBase64Encoded: false,
  14. statusCode: '200',
  15. headers: {
  16. 'x-custom-header': 'header value'
  17. },
  18. body: content
  19. };
  20. callback(null, response)
  21. };

Python

  1. # -*- coding: utf-8 -*-
  2. import json
  3. def handler(event, context):
  4. event = json.loads(event)
  5. content = {
  6. 'path': event['path'],
  7. 'method': event['httpMethod'],
  8. 'headers': event['headers'],
  9. 'queryParameters': event['queryParameters'],
  10. 'pathParameters': event['pathParameters'],
  11. 'body': event['body']
  12. }
  13. # you can deal with your own logic here.
  14. rep = {
  15. "isBase64Encoded": "false",
  16. "statusCode": "200",
  17. "headers": {
  18. "x-custom-header": "no"
  19. },
  20. "body": content
  21. }
  22. return json.dumps(rep)

Php

  1. <?php
  2. function handler($event, $context) {
  3. $event = json_decode($event, $assoc = true);
  4. $content = [
  5. 'path' => $event['path'],
  6. 'method' => $event['httpMethod'],
  7. 'headers' => $event['headers'],
  8. 'queryParameters' => $event['queryParameters'],
  9. 'pathParameters' => $event['pathParameters'],
  10. 'body' => $event['body'],
  11. ];
  12. $rep = [
  13. "isBase64Encoded" => "false",
  14. "statusCode" => "200",
  15. "headers" => [
  16. "x-custom-header" => "no",
  17. ],
  18. "body" => $content,
  19. ];
  20. return json_encode($rep);
  21. }

Java

使用 Java 编程时,必须要实现一个类,它要实现函数计算预定义的接口,目前有 2 个预定义的接口可以实现(您任选其一即可):

  • 函数计算 Java 运行环境请参考文章 Java Runtime
使用 PojoRequestHandler<I, O> 接口(推荐)
  1. import com.aliyun.fc.runtime.Context;
  2. import com.aliyun.fc.runtime.PojoRequestHandler;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. public class ApiTriggerDemo implements PojoRequestHandler<ApiRequest, ApiResponse> {
  6. public ApiResponse handleRequest(ApiRequest request, Context context) {
  7. // Get ApiRequest info
  8. context.getLogger().info(request.toString());
  9. String path = request.getPath();
  10. String httpMethod = request.getHttpMethod();
  11. String body = request.getBody();
  12. context.getLogger().info("path:" + path);
  13. context.getLogger().info("httpMethod:" + httpMethod);
  14. context.getLogger().info("body:" + body);
  15. // Deal with your own logic here
  16. // ApiResponse example
  17. Map headers = new HashMap();
  18. boolean isBase64Encoded = false;
  19. int statusCode = 200;
  20. String returnBody = "";
  21. return new ApiResponse(headers,isBase64Encoded,statusCode,returnBody);
  22. }
  23. }

两个pojo类,ApiRequest类和ApiResponse类如下。注意pojo类的set()get()方法注意要写全。

  1. import java.util.Map;
  2. public class ApiRequest {
  3. private String path;
  4. private String httpMethod;
  5. private Map headers;
  6. private Map queryParameters;
  7. private Map pathParameters;
  8. private String body;
  9. private boolean isBase64Encoded;
  10. @Override
  11. public String toString() {
  12. return "Request{" +
  13. "path='" + path + '\'' +
  14. ", httpMethod='" + httpMethod + '\'' +
  15. ", headers=" + headers +
  16. ", queryParameters=" + queryParameters +
  17. ", pathParameters=" + pathParameters +
  18. ", body='" + body + '\'' +
  19. ", isBase64Encoded=" + isBase64Encoded +
  20. '}';
  21. }
  22. public String getPath() {
  23. return path;
  24. }
  25. public void setPath(String path) {
  26. this.path = path;
  27. }
  28. public String getHttpMethod() {
  29. return httpMethod;
  30. }
  31. public void setHttpMethod(String httpMethod) {
  32. this.httpMethod = httpMethod;
  33. }
  34. public Map getHeaders() {
  35. return headers;
  36. }
  37. public void setHeaders(Map headers) {
  38. this.headers = headers;
  39. }
  40. public Map getQueryParameters() {
  41. return queryParameters;
  42. }
  43. public void setQueryParameters(Map queryParameters) {
  44. this.queryParameters = queryParameters;
  45. }
  46. public Map getPathParameters() {
  47. return pathParameters;
  48. }
  49. public void setPathParameters(Map pathParameters) {
  50. this.pathParameters = pathParameters;
  51. }
  52. public String getBody() {
  53. return body;
  54. }
  55. public void setBody(String body) {
  56. this.body = body;
  57. }
  58. public boolean getIsBase64Encoded() {
  59. return this.isBase64Encoded;
  60. }
  61. public void setIsBase64Encoded(boolean base64Encoded) {
  62. this.isBase64Encoded = base64Encoded;
  63. }
  64. }
  1. import java.util.Map;
  2. public class ApiResponse {
  3. private Map headers;
  4. private boolean isBase64Encoded;
  5. private int statusCode;
  6. private String body;
  7. public ApiResponse(Map headers, boolean isBase64Encoded, int statusCode, String body) {
  8. this.headers = headers;
  9. this.isBase64Encoded = isBase64Encoded;
  10. this.statusCode = statusCode;
  11. this.body = body;
  12. }
  13. public Map getHeaders() {
  14. return headers;
  15. }
  16. public void setHeaders(Map headers) {
  17. this.headers = headers;
  18. }
  19. public boolean getIsBase64Encoded() {
  20. return isBase64Encoded;
  21. }
  22. public void setIsBase64Encoded(boolean base64Encoded) {
  23. this.isBase64Encoded = base64Encoded;
  24. }
  25. public int getStatusCode() {
  26. return statusCode;
  27. }
  28. public void setStatusCode(int statusCode) {
  29. this.statusCode = statusCode;
  30. }
  31. public String getBody() {
  32. return body;
  33. }
  34. public void setBody(String body) {
  35. this.body = body;
  36. }
  37. }

pom.xml文件如下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>apiTrigger</groupId>
  7. <artifactId>apiTrigger</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <build>
  10. <plugins>
  11. <plugin>
  12. <groupId>org.apache.maven.plugins</groupId>
  13. <artifactId>maven-compiler-plugin</artifactId>
  14. <configuration>
  15. <source>1.8</source>
  16. <target>1.8</target>
  17. </configuration>
  18. </plugin>
  19. </plugins>
  20. </build>
  21. <dependencies>
  22. <dependency>
  23. <groupId>com.aliyun.fc.runtime</groupId>
  24. <artifactId>fc-java-core</artifactId>
  25. <version>1.0.0</version>
  26. </dependency>
  27. </dependencies>
  28. </project>

使用StreamRequestHandler接口

使用 StreamRequestHandler 接口示例如下,需要将输入的 InputStream 转换为对应的 POJO 类,pom.xml 文件配置与使用 PojoRequestHandler<I, O> 接口相同。

代码如下:

  1. import com.aliyun.fc.runtime.Context;
  2. import com.aliyun.fc.runtime.StreamRequestHandler;
  3. import com.aliyun.fc.runtime.Context;
  4. import com.google.gson.Gson;
  5. import java.io.*;
  6. import java.util.Base64;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. public class ApiTriggerDemo2 implements StreamRequestHandler {
  10. public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) {
  11. try {
  12. // Convert InputStream to string
  13. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  14. StringBuffer stringBuffer = new StringBuffer();
  15. String string = "";
  16. while ((string = bufferedReader.readLine()) != null) {
  17. stringBuffer.append(string);
  18. }
  19. String input = stringBuffer.toString();
  20. context.getLogger().info("inputStream: " + input);
  21. Request req = new Gson().fromJson(input, Request.class);
  22. context.getLogger().info("input req: ");
  23. context.getLogger().info(req.toString());
  24. String bodyReq = req.getBody();
  25. Base64.Decoder decoder = Base64.getDecoder();
  26. context.getLogger().info("body: " + new String(decoder.decode(bodyReq)));
  27. // Deal with your own logic here
  28. // construct response
  29. Map headers = new HashMap();
  30. headers.put("x-custom-header", " ");
  31. boolean isBase64Encoded = false;
  32. int statusCode = 200;
  33. Map body = new HashMap();
  34. Response resp = new Response(headers, isBase64Encoded, statusCode, body);
  35. String respJson = new Gson().toJson(resp);
  36. context.getLogger().info("outputStream: " + respJson);
  37. outputStream.write(respJson.getBytes());
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. } finally {
  41. try {
  42. outputStream.close();
  43. inputStream.close();
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. }
  49. class Request {
  50. private String path;
  51. private String httpMethod;
  52. private Map headers;
  53. private Map queryParameters;
  54. private Map pathParameters;
  55. private String body;
  56. private boolean isBase64Encoded;
  57. @Override
  58. public String toString() {
  59. return "Request{" +
  60. "path='" + path + '\'' +
  61. ", httpMethod='" + httpMethod + '\'' +
  62. ", headers=" + headers +
  63. ", queryParameters=" + queryParameters +
  64. ", pathParameters=" + pathParameters +
  65. ", body='" + body + '\'' +
  66. ", isBase64Encoded=" + isBase64Encoded +
  67. '}';
  68. }
  69. public String getBody() {
  70. return body;
  71. }
  72. }
  73. // FC need to return the response to API gateway in the following JSON format
  74. class Response {
  75. private Map headers;
  76. private boolean isBase64Encoded;
  77. private int statusCode;
  78. private Map body;
  79. public Response(Map headers, boolean isBase64Encoded, int statusCode, Map body) {
  80. this.headers = headers;
  81. this.isBase64Encoded = isBase64Encoded;
  82. this.statusCode = statusCode;
  83. this.body = body;
  84. }
  85. }
  86. }

API 网关的传入参数格式

当以函数计算作为 API 网关的后端服务时,API 网关会把请求参数通过一个固定结构传给函数计算的入参 event ,函数计算通过如下结构去获取需要的参数,然后进行处理,该结构如下:

  1. {
  2. "path":"api request path",
  3. "httpMethod":"request method name",
  4. "headers":{all headers,including system headers},
  5. "queryParameters":{query parameters},
  6. "pathParameters":{path parameters},
  7. "body":"string of request payload",
  8. "isBase64Encoded":"true|false, indicate if the body is Base64-encode"
  9. }

函数计算的返回参数格式

函数计算需要将输出内容通过如下 JSON 格式返回给 API 网关,方便 API 网关解析。

  1. {
  2. "isBase64Encoded":true|false,
  3. "statusCode":httpStatusCode,
  4. "headers":{response headers},
  5. "body":"..."
  6. }

下一步:

步骤三:测试函数