通过函数计算的 Custom Runtime,可以将 Go 项目一键部署至函数计算。本文介绍快速部署和调用函数的详细步骤。

前提条件

您已完成以下操作:
说明 如果您已安装 Funcraft 可直接跳转至步骤二:部署和调用函数

步骤一:准备环境

安装 Funcraft,最简单的方式就是直接下载可执行的二进制文件。

  1. 安装 Funcraft 到本机。详情请参见安装文档
  2. 执行 fun --version 检查安装是否成功。
  3. 执行 fun config 配置 Funcraft。然后按照提示依次配置 Account IDAccess Key IDAccess Key SecretDefault region name
    $ fun config
    Aliyun Account ID 1234xxx
    Aliyun Access Key ID xxxx
    Aliyun Access Key Secret xxxx
    Default region name cn-xxxx
    The timeout in seconds for each SDK client invoking 300
    The maximum number of retries for each SDK client 5
    Allow to anonynously report usage statistics to improve the tool over time? (Y/n)

步骤二:部署和调用函数

  1. 执行以下命令克隆示例工程到本地。
    git clone https://github.com/awesome-fc/fc-custom-demo          
    说明 如果您没有安装 git,可以直接在浏览器地址栏输入 https://github.com/awesome-fc/fc-custom-demo,然后单击下载按钮直接下载。
  2. 执行以下命令进入克隆的示例项目中。
    cd go_demo
  3. 执行以下命令部署函数。
    $ make deploy
    docker build -t fc-go-runtime  -f build-image/Dockerfile build-image
    Sending build context to Docker daemon  3.072kB
    Step 1/5 : FROM golang:1.12.16-stretch
     ---> 7ad03a8aece5
    ...
    Step 5/5 : RUN go get github.com/awesome-fc/golang-runtime
     ---> Using cache
     ---> 262e7f38ac05
    Successfully built 262e7f38ac05
    Successfully tagged fc-go-runtime:latest
    docker run -it -v $(pwd):/tmp fc-go-runtime bash -c "go build -o /tmp/code//bootstrap /tmp/code/main.go"
    chmod +x code/bootstrap
    fun deploy -y
    using template: template.yml
    ···
    Waiting for service go_demo to be deployed...
            Waiting for function fc_go to be deployed...
                    Waiting for packaging function fc_go code...
                    The function fc_go has been packaged. A total of 1 file were compressed and the final size was 3.76 MB
            function fc_go deploy success
    service go_demo deploy success
  4. 执行以下命令调用部署的函数。
    $ fun invoke -e "Hello World"
    ...
    ========= FC invoke Logs begin =========
    FC Invoke Start RequestId: 4c1451b2-f29b-4554-87e5-126f3bc11fcf
    2020-04-07T02:53:01.981Z: 4c1451b2-f29b-4554-87e5-126f3bc11fcf [INFO]  hello golang!
    FC Invoke End RequestId: 4c1451b2-f29b-4554-87e5-126f3bc11fcf
    
    Duration: 1.03 ms, Billed Duration: 100 ms, Memory Size: 512 MB, Max Memory Used: 4.39 MB
    ========= FC invoke Logs end =========
    
    FC Invoke Result:
    Hello World

更多信息

如果您需将 Go 应用框架一键迁移到函数计算,请参见以下文档: