不了解Vercel的朋友可以先浏览上一篇文章 Vercel-免费Web应用托管平台
上文提到Vercel支持Python、Go、NodeJS、Ruby、PHP等语言的Serverless函数编写,下面就来尝试一下Serverless部署的过程。

环境准备

以下步骤自行解决,不再赘述

1
2
3
建个git仓库
拉到本地,导入IDE
安装各语言的SDK和IDE插件

编写配置文件

创建vercel.json,填入以下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
"headers": [
{
"source": "/(.*)",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "*"
},
{
"key": "Access-Control-Allow-Headers",
"value": "content-type"
},
{
"key": "Access-Control-Allow-Methods",
"value": "DELETE,PUT,POST,GET,OPTIONS"
}
]
}
],
"rewrites": [
{
"source": "/(.*)",
"destination": "api/index"
}
]
}

这里headers默认为跨域配置,rewrites映射的是路径和目录

编写函数文件

创建api/index.js,填入以下内容

index.js

1
2
3
4
export default function handler(request, response) {
const { name } = request.query;
response.end(`Hello ${name}!`);
}

相应的,如果你是其他语言的函数,就建立对应的函数文件

index.go

1
2
3
4
5
6
7
8
9
10
11
12
package handler

import (
"fmt"
"net/http"
"time"
)

func Handler(w http.ResponseWriter, r *http.Request) {
currentTime := time.Now().Format(time.RFC850)
fmt.Fprintf(w, currentTime)
}

index.py

1
2
3
4
5
6
7
8
9
10
11
from http.server import BaseHTTPRequestHandler
from datetime import datetime

class handler(BaseHTTPRequestHandler):

def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')).encode())
return

index.rb

1
2
3
4
5
Handler = Proc.new do |req, res|
res.status = 200
res['Content-Type'] = 'text/text; charset=utf-8'
res.body = "Current Time: #{Time.new}"
end

index.php

1
2
<?php
echo "php test";

如果你编写的是PHP函数,需要在配置里添加以下内容,构建的时候才能引入PHP扩展包

1
2
3
4
5
6
7
8
"functions": {
"api/index.php": {
"runtime": "[email protected]",
"excludeFiles": "{test/**}",
"memory": 256,
"maxDuration": 5
}
}

* 写完记得push到git仓库

构建和部署

1)进入Dashboard,点击右手边Add New...按钮,选择Project
2)选择从github(Import Git Repository
3)模板选择Other,点击Deploy

部署成功后,快照图片会显示代码中的打印结果,你同样可以点击DOMAINS下方链接进行api测试