完成创建HTTP触发器后,您可以开始编写函数代码。本文介绍如何使用函数计算控制台编写函数。

前提条件

创建触发器

操作步骤

  1. 登录函数计算控制台
  2. 在顶部菜单栏,选择地域。
  3. 在左侧导航栏,单击服务/函数
  4. 找到目标服务下的目标函数,单击函数名称。
  5. 单击代码执行页签,在代码编辑器中编写代码。
    代码示例如下:
    var getRawBody = require('raw-body')
    module.exports.handler = function (request, response, context) {
        // get request info
        getRawBody(request, function (err, data) {
            var params = {
                path: request.path,
                queries: request.queries,
                headers: request.headers,
                method: request.method,
                body: data,
                url: request.url,
                clientIP: request.clientIP,
            }
            // you can deal with your own logic here
            // set response
            var respBody = new Buffer.from(JSON.stringify(params));
            // var respBody = new Buffer( )
            response.setStatusCode(200)
            response.setHeader('content-type', 'application/json')
            response.send(respBody)
        })
    };
    # -*- coding: utf-8 -*-
    import json
    HELLO_WORLD = b"Hello world!\n"
    def handler(environ, start_response):
        request_uri = environ['fc.request_uri']
        response_body = {
          'uri':environ['fc.request_uri'],
          'method':environ['REQUEST_METHOD']
        }
        # do something here
        status = '200 OK'
        response_headers = [('Content-type', 'text/json')]
        start_response(status, response_headers)
        # Python2
        return [json.dumps(response_body)]
        # Python3 tips: When using Python3, the str and bytes types cannot be mixed.
        # Use str.encode() to go from str to bytes
        # return [json.dumps(response_body).encode()]
    <?php
    use RingCentral\Psr7\Response;
    function handler($request, $context): Response{
        /*
        $body       = $request->getBody()->getContents();
        $queries    = $request->getQueryParams();
        $method     = $request->getMethod();
        $headers    = $request->getHeaders();
        $path       = $request->getAttribute("path");
        $requestURI = $request->getAttribute("requestURI");
        $clientIP   = $request->getAttribute("clientIP");
        */
        return new Response(
            200,
            array(
                "custom_header1" => "v1",
                "custom_header2" => ["v2", "v3"],
            ),
            "hello world"
        );
    }

后续步骤

测试函数