大概
cgi写复杂的webapi太麻烦了,或者本身应用就已经内置又服务了。自己应用内置服务又跟飞牛不同源,没法使用飞牛鉴权,也没法获取主题配色参数
那我们可以使用cgi实现一个代理,代理到自己的服务,实现同源,以下是简单实现介绍
入口
入口填 /cgi/ThirdParty/{appname}/proxy.cgi/,例如我在线fpk的配置
{
".url": {
"fnpackup.proxy.Application": {
"title": "在线fpk",
"icon": "images/icon_{0}.png",
"type": "iframe",
"protocol": "http",
"port": "",
"url": "/cgi/ThirdParty/fnpackup/proxy.cgi/",
"allUsers": true
}
}
}
代理
在app/ui文件夹里新建 proxy.cgi,写入以下代码,这是一个简单的实现,示例代码只代理了cookie和content-type头,get 和 post 方法,大多数情况下都够用了,需要代理其它的可以加上
#!/bin/bash
# cgi名字,替换成你自己的
cgi_name="proxy.cgi"
# 你的服务,改成你自己的服务端口即可
target_url="http://localhost:1069";
if [[ "$REQUEST_URI" == *"$cgi_name"* ]]; then
after_proxy="${REQUEST_URI#*$cgi_name}"
if [[ "$after_proxy" == *"?"* ]]; then
target_path=$(echo "$after_proxy" | cut -d'?' -f1)
target_query=$(echo "$after_proxy" | cut -d'?' -f2-)
else
target_path="$after_proxy"
target_query=""
fi
else
after_proxy=""
target_path=""
target_query="$QUERY_STRING"
fi
if [ -z "$target_path" ]; then
target_path="/"
fi
target_url="$target_url$target_path"
if [ -n "$target_query" ]; then
target_url="$target_url?$target_query"
fi
curl_args=(-s --include -X "$REQUEST_METHOD")
if [ -n "$HTTP_COOKIE" ]; then
curl_args+=(-H "Cookie: $HTTP_COOKIE")
fi
if [ -n "$CONTENT_TYPE" ]; then
curl_args+=(-H "Content-Type: $CONTENT_TYPE")
fi
curl_args+=("$target_url")
if [ "$REQUEST_METHOD" = "POST" ]; then
exec cat | curl "${curl_args[@]}" --data-binary @- --include | sed -e '/^HTTP\/1.1 100/,/^\r\?$/d'
else
exec curl "${curl_args[@]}" --include | sed -e '/^HTTP\/1.1 100/,/^\r\?$/d'
fi
访问
proxy.cgi后面的部分被原样代理到目标服务,例如 /cgi/ThirdParty/fnpackup/proxy.cgi/aaa/bbb?a=1 被代理为 http://localhost:1069/aaa/bbb?a=1