Merge branch 'feature/hanshuo'

# Conflicts:
#	build/cmd/Dockerfile
#	build/resources/Dockerfile
#	build/resources/auto-join.sh
#	build/resources/auto-start.sh
This commit is contained in:
Liujian
2024-12-03 10:32:51 +08:00
27 changed files with 3085 additions and 22 deletions

View File

@@ -34,6 +34,7 @@ import (
"github.com/eolinker/apinto/drivers/discovery/eureka"
"github.com/eolinker/apinto/drivers/discovery/nacos"
"github.com/eolinker/apinto/drivers/discovery/static"
auth_interceptor "github.com/eolinker/apinto/drivers/plugins/auth-interceptor"
data_mask_strategy "github.com/eolinker/apinto/drivers/strategy/data-mask-strategy"
"github.com/eolinker/apinto/application/auth"
@@ -82,6 +83,7 @@ func driverRegister(extenderRegister eosc.IExtenderDriverRegister) {
// 应用
app.Register(extenderRegister)
auth.Register(extenderRegister)
auth_interceptor.Register(extenderRegister)
// 插件相关
plugin_manager.Register(extenderRegister)

View File

@@ -23,6 +23,7 @@ import (
response_filter "github.com/eolinker/apinto/drivers/plugins/response-filter"
response_rewrite_v2 "github.com/eolinker/apinto/drivers/plugins/response-rewrite_v2"
rsa_filter "github.com/eolinker/apinto/drivers/plugins/rsa-filter"
script_handler "github.com/eolinker/apinto/drivers/plugins/script-handler"
data_mask "github.com/eolinker/apinto/drivers/plugins/strategy/data-mask"
access_log "github.com/eolinker/apinto/drivers/plugins/access-log"
@@ -118,4 +119,6 @@ func pluginRegister(extenderRegister eosc.IExtenderDriverRegister) {
// ai相关插件
ai_prompt.Register(extenderRegister)
ai_formatter.Register(extenderRegister)
script_handler.Register(extenderRegister)
}

View File

@@ -0,0 +1,118 @@
package logs
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"testing"
"time"
)
type LokiRequest struct {
Streams []*Stream `json:"streams"`
}
type Stream struct {
Stream map[string]string `json:"stream"`
Values [][]interface{} `json:"values"`
}
func TestSendLogToLoki(t *testing.T) {
// 1. Create a new log
// 2. Send the log to Loki
// 3. Check if the log is in Loki
items, err := parseLog()
if err != nil {
t.Fatal(err)
}
client := http.Client{}
for _, item := range items {
body, err := json.Marshal(item)
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequest(http.MethodPost, "http://localhost:3100/loki/api/v1/push", bytes.NewBuffer(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Scope-OrgID", "tenant1")
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != 204 {
t.Fatal(resp.StatusCode, string(respBody))
}
if err := resp.Body.Close(); err != nil {
t.Fatal(err)
}
}
t.Log("Send log to Loki success")
}
func parseLog() ([]*LokiRequest, error) {
data, err := os.ReadFile("access.log")
if err != nil {
return nil, err
}
// 换行分割
lines := strings.Split(string(data), "\n")
reqMap := map[string]*Stream{}
// 解析日志
for _, l := range lines {
if l == "" {
continue
}
tmp := make(map[string]interface{})
err = json.Unmarshal([]byte(l), &tmp)
if err != nil {
return nil, err
}
org := map[string]string{
"cluster": tmp["cluster"].(string),
"node": tmp["node"].(string),
"service": tmp["service"].(string),
"api": tmp["api"].(string),
"src_ip": tmp["src_ip"].(string),
"block_name": tmp["block_name"].(string),
}
key := genKey(org)
if _, ok := reqMap[key]; !ok {
reqMap[key] = &Stream{
Stream: org,
Values: make([][]interface{}, 0),
}
}
reqMap[key].Values = append(reqMap[key].Values, []interface{}{strconv.FormatInt(time.UnixMilli(int64(tmp["msec"].(float64))).UnixNano(), 10), l})
}
reqs := make([]*LokiRequest, len(reqMap)/10+1)
num := 0
for _, v := range reqMap {
index := num / 10
if reqs[index] == nil {
reqs[index] = &LokiRequest{
Streams: make([]*Stream, 0, 10),
}
}
reqs[index].Streams = append(reqs[index].Streams, v)
num++
}
return reqs, nil
}
func genKey(org map[string]string) string {
return fmt.Sprintf("cluster_%s-node_%s-service_%s-api_%s-src_ip_%s-block_name_%s", org["cluster"], org["node"], org["service"], org["api"], org["src_ip"], org["block_name"])
}

View File

@@ -0,0 +1,17 @@
package para_hmac
import (
"net/url"
"testing"
)
func TestSign(t *testing.T) {
appId := "ed3DtlYh"
appKey := "3YnxRNwULya0W56A"
sequenceNo := "2024103117392905280623"
timestamp := "20241031173929052"
body := "{\"agentId\":\"nx\"}"
t.Log(url.PathUnescape("qqY%2BkJ2LUany%2FSZf3a3Rd73scYsEXDGRoeF5FPuZJ2g%3D"))
t.Log(sign(appId, appKey, timestamp, sequenceNo, body))
}

View File

@@ -1,12 +1,12 @@
# 名称apinto镜像携带了部署k8s集群所需要的脚本
# 创建时间2022-3-30
# 创建时间2024-11-19
FROM alpine:latest
RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine|https://mirrors.aliyun.com/alpine|g' /etc/apk/repositories \
&& apk update \
&& apk add --no-cache bash tzdata
RUN apk add --no-cache netcat-openbsd curl
RUN apk add --no-cache netcat-openbsd
ENV TZ=Asia/Shanghai
@@ -25,9 +25,9 @@ RUN tar -zxvf apinto.linux.x64.tar.gz && ls /${AppName} / && rm -rf ../apinto.li
#复制程序默认配置文件以及修改脚本权限
RUN mkdir /etc/${AppName}
RUN cp /${AppName}/${AppName}.yml.tpl /etc/${AppName}/${AppName}.yml && cp /${AppName}/config.yml.tpl /etc/${AppName}/config.yml
RUN chmod 777 /${AppName}/*
WORKDIR /${AppName}
RUN chmod 777 /${AppName}/*.sh
#容器启动命令
CMD bash "auto-start.sh"
WORKDIR /apinto
CMD ["bash","/apinto/auto-start.sh"]

View File

@@ -0,0 +1,33 @@
# 名称apinto镜像携带了部署k8s集群所需要的脚本
# 创建时间2024-11-19
FROM alpine:latest
RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine|https://mirrors.aliyun.com/alpine|g' /etc/apk/repositories \
&& apk update \
&& apk add --no-cache bash tzdata
RUN apk add --no-cache netcat-openbsd
ENV TZ=Asia/Shanghai
RUN cp /usr/share/zoneinfo/${TZ} /etc/localtime && echo ${TZ} > /etc/timezone
#设置环境变量
ARG AppName=apinto
#定义数据卷
VOLUME /var/lib/${AppName}
#解压网关程序压缩包
COPY ./apinto.linux.x64.tar.gz /
RUN tar -zxvf apinto.linux.x64.tar.gz && ls /${AppName} / && rm -rf ../apinto.linux.x64.tar.gz
#复制程序默认配置文件以及修改脚本权限
RUN mkdir /etc/${AppName}
RUN cp /${AppName}/${AppName}.yml.tpl /etc/${AppName}/${AppName}.yml && cp /${AppName}/config.yml.tpl /etc/${AppName}/config.yml
RUN chmod 777 /${AppName}/*.sh
WORKDIR /apinto
CMD ["bash","/apinto/auto-start.sh"]

View File

@@ -1,38 +1,60 @@
#!/bin/sh
ERR_LOG=/var/log/apinto/error.log
echo_info() {
echo "[$(date "+%Y-%m-%d %H:%M:%S")] [INFO] $1" >> $ERR_LOG
}
echo_error() {
echo "[$(date "+%Y-%m-%d %H:%M:%S")] [ERROR] $1" >> $ERR_LOG
}
# 解析当前 Pod 的序号
CURRENT_INDEX=${HOSTNAME##*-}
BASE_NAME=${HOSTNAME%-*}
# 检查当前程序是否启动,若无,则等待
until curl --max-time 5 --silent --fail http://127.0.0.1:9400; do
echo_info "Waiting for localhost to be ready..."
sleep 1
done
# 如果当前是 apinto-0需要特殊处理
if [ "$CURRENT_INDEX" -eq 0 ]; then
echo "This is ${HOSTNAME}. Checking if other nodes exist..."
echo_info "This is ${HOSTNAME}. Checking if other nodes exist..."
# 尝试连接 apinto-1
NEXT_POD="${HOSTNAME}.${SERVICE}.${NAMESPACE}.svc.cluster.local"
if nc -zv ${NEXT_POD} 9400; then
echo "Found a running node: ${NEXT_POD}. Joining the cluster..."
./apinto join ${NEXT_POD}
NEXT_POD="${BASE_NAME}-$((CURRENT_INDEX + 1)).${SERVICE}.${NAMESPACE}.svc.cluster.local"
if curl --max-time 5 --silent --fail http://${NEXT_POD}:9401; then
echo_info "Found a running node: ${NEXT_POD}. Joining the cluster..."
./apinto join -addr ${NEXT_POD}:9401 >> $ERR_LOG 2>&1
if [ $? -ne 0 ]; then
echo_error "Error: Failed to join the cluster."
fi
else
echo "No other nodes are available. Starting as the first node."
echo_info "No other nodes are available. Starting as the first node."
fi
else
# 对于非 apinto-0 的 Pod连接到前一个 Pod
PREVIOUS_POD="${BASE_NAME}-$((CURRENT_INDEX - 1)).${SERVICE}.${NAMESPACE}.svc.cluster.local"
echo "This is $HOSTNAME. Waiting for $PREVIOUS_POD to be ready..."
echo_info "This is $HOSTNAME. Waiting for $PREVIOUS_POD to be ready..."
until nc -zv $PREVIOUS_POD 9400; do
echo "Waiting for $PREVIOUS_POD to be ready..."
sleep 5
until curl --max-time 5 --silent --fail http://$PREVIOUS_POD:9401; do
echo_info "Waiting for $PREVIOUS_POD to be ready..."
sleep 1
done
echo "$PREVIOUS_POD is ready. Joining the cluster..."
./apinto join $PREVIOUS_POD
echo_info "$PREVIOUS_POD is ready. Joining the cluster..."
./apinto join -addr $PREVIOUS_POD:9401 >> $ERR_LOG 2>&1
if [ $? -ne 0 ]; then
echo_error "Error: Failed to join the cluster."
fi
fi
if [ $? -ne 0 ]; then
echo "Error: Failed to join the cluster."
echo_error "Error: Failed to join the cluster."
exit 1
fi
echo "Successfully joined the cluster."
echo_info "Successfully joined the cluster."

View File

@@ -6,6 +6,15 @@ set -e # 在命令失败时退出
APINTO_LOG_DIR="/var/log/apinto"
APINTO_LOG_FILE="$APINTO_LOG_DIR/error.log"
if [[ "${HOSTNAME}" != "" && ${SERVICE} != "" && ${NAMESPACE} != "" ]];then
# 替换配置文件中的 {IP}
CONFIG_FILE="/etc/apinto/config.yml"
IP=${HOSTNAME}.${SERVICE}.${NAMESPACE}.svc.cluster.local
cp -f config.yml.k8s.tpl ${CONFIG_FILE}
sed -i "s/{IP}/${IP}/g" "$CONFIG_FILE"
echo "Replaced {IP} with ${IP} in $CONFIG_FILE."
fi
# 启动 Apinto
echo "Starting Apinto..."
./apinto start

View File

@@ -0,0 +1,26 @@
version: 2
#certificate: # 证书存放根目录
# dir: /etc/apinto/cert
client:
#advertise_urls: # open api 服务的广播地址
#- http://127.0.0.1:9400
listen_urls: # open api 服务的监听地址
- http://0.0.0.0:9400
#certificate: # 证书配置允许使用ip的自签证书
# - cert: server.pem
# key: server.key
gateway:
#advertise_urls: # 转发服务的广播地址
#- http://127.0.0.1:9400
listen_urls: # 转发服务的监听地址
- https://0.0.0.0:8099
- http://0.0.0.0:8099
peer: # 集群间节点通信配置信息
listen_urls: # 节点监听地址
- http://0.0.0.0:9401
advertise_urls: # 节点通信广播地址
- http://{IP}:9401
#certificate: # 证书配置允许使用ip的自签证书
# - cert: server.pem
# key: server.key

47
build/resources/join.sh.bak Executable file
View File

@@ -0,0 +1,47 @@
#!/bin/bash
set -xe
#This script is used to join the K8S cluster
sleep 10s
#Gets the IP addresses of all pods under the target service
response=$(curl -s "https://kubernetes.default.svc:443/api/v1/namespaces/${SVC_NAMESPACE}/endpoints/${SVC_NAME}" -k -H "Authorization: Bearer ${SVC_TOKEN}")
#Determines whether the request was successful
if [[ ${response} =~ 'Failure' ]]
then
echo ${response}
exit 0
fi
set +e
#Check whether there is a POD ID in the result
{
hostnames=$( echo ${response} | jq -r '.subsets[].addresses[].hostname' )
} || {
exit 0
}
podHostName=$(hostname)
#If the ips is null
if [[ "$( echo ${hostnames} )" == '' ]]
then
echo "There are no pods ip in Service "
exit 1
fi
set -e
#Traverses all the Node's IP
for hn in ${hostnames}
do
if [ ${hn} != ${podHostName} ]
then
#join the cluster
return_info=$(./apinto join --addr=${hn}.${SVC_NAME}:${APINTO_ADMIN_PORT})
if [[ $return_info = '' ]]
then
break
fi
fi
done

View File

@@ -0,0 +1,11 @@
package loki
import "github.com/eolinker/eosc"
type Config struct {
Url string `json:"url" yaml:"url" label:"请求地址"`
Method string `json:"method" label:"请求方法" enum:"POST,PUT" default:"POST"`
Scopes []string `json:"scopes" label:"作用域"`
Headers map[string]string `json:"headers" yaml:"headers" label:"请求头"`
Formatter eosc.FormatterConfig `json:"formatter" yaml:"formatter" label:"格式化配置"`
}

View File

@@ -0,0 +1 @@
package loki

View File

@@ -0,0 +1,27 @@
package loki
import (
"bytes"
"net/http"
"github.com/eolinker/eosc"
)
type Output struct {
url string
method string
headers map[string]string
formatter eosc.IFormatter
}
func (o *Output) Output(entry eosc.IEntry) error {
return eosc.ErrorWorkerNotRunning
}
func (o *Output) genRequest(body []byte) (*http.Request, error) {
req, err := http.NewRequest(o.method, o.url, bytes.NewReader(body))
if err != nil {
}
}

View File

@@ -0,0 +1,166 @@
package auth_interceptor
import (
"encoding/json"
"fmt"
"mime"
"time"
"github.com/eolinker/apinto/drivers"
"github.com/eolinker/eosc"
"github.com/eolinker/eosc/eocontext"
http_service "github.com/eolinker/eosc/eocontext/http-context"
)
type Auth struct {
cfg *Config
redisConn string
drivers.WorkerBase
}
func (a *Auth) Destroy() {
redisPool.Release(a.redisConn)
return
}
// DoFilter 拦截请求过滤内部转换为http类型再处理
func (a *Auth) DoFilter(ctx eocontext.EoContext, next eocontext.IChain) (err error) {
return http_service.DoHttpFilter(a, ctx, next)
}
// Start 插件添加时执行
func (a *Auth) Start() error {
return nil
}
// Reset 当类型为插件时Reset方法不会执行
func (a *Auth) Reset(conf interface{}, workers map[eosc.RequireId]eosc.IWorker) error {
return nil
}
// Stop 插件删除时间执行
func (a *Auth) Stop() error {
return nil
}
func (a *Auth) CheckSkill(skill string) bool {
return http_service.FilterSkillName == skill
}
// DoHttpFilter 核心http处理方法
func (a *Auth) DoHttpFilter(ctx http_service.IHttpContext, next eocontext.IChain) error {
err := a.addAuthToProxy(ctx)
if err != nil {
ctx.Response().SetStatus(401, "Unauthorized")
ctx.Response().SetBody([]byte(err.Error()))
return err
}
err = next.DoChain(ctx)
if err != nil {
return err
}
if ctx.Response().StatusCode() == 401 {
client := redisPool.Get(a.redisConn)
client.Del(ctx.Context(), a.cfg.SysKey).Result()
err = a.addAuthToProxy(ctx)
if err != nil {
ctx.Response().SetStatus(401, "Unauthorized")
ctx.Response().SetBody([]byte(err.Error()))
return err
}
return next.DoChain(ctx)
}
return nil
}
func (a *Auth) addAuthToProxy(ctx http_service.IHttpContext) error {
var token string
var err error
client := redisPool.Get(a.redisConn)
for i := 0; i < a.cfg.RetryCount+1; i++ {
token, err = client.Get(ctx.Context(), a.cfg.SysKey).Result()
if err == nil {
break
}
time.Sleep(time.Duration(a.cfg.RetryPeriod) * time.Second)
}
if token == "" || err != nil {
client.Del(ctx.Context(), a.cfg.SysKey)
return fmt.Errorf("[plugin auth-interceptor invoke err] get token failed")
}
switch a.cfg.AuthPosition {
case positionHeader:
ctx.Proxy().Header().SetHeader(a.cfg.AuthKey, token)
case positionBody:
// 如果是json类型的body需要解析后再添加auth
contentType, _, _ := mime.ParseMediaType(ctx.Proxy().Body().ContentType())
switch contentType {
case "application/x-www-form-urlencoded", "multipart/form-data":
ctx.Proxy().Body().SetToForm(a.cfg.AuthKey, token)
case "application/json":
var body = make(map[string]interface{})
bytes, _ := ctx.Proxy().Body().RawBody()
err = json.Unmarshal(bytes, &body)
if err != nil {
return fmt.Errorf("[plugin auth-interceptor invoke err] unmarshal body failed")
}
body[a.cfg.AuthKey] = token
rebody, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("[plugin auth-interceptor invoke err] marshal body failed")
} else {
ctx.Proxy().Body().SetRaw(ctx.Request().ContentType(), rebody)
}
}
case positionQuery:
ctx.Proxy().URI().SetQuery(a.cfg.AuthKey, token)
}
return nil
}
//
//// 添加auth头
//func AddAuth(a *Auth, ctx http_service.IHttpContext) {
// var token, err = GetAuth(a.cfg)
// // 如果没有认证字符串或错误,删除认证字符串,等待远程重新获取认证字符串
// if token == "" && err != nil {
// removeAuth(a.cfg)
// }
// // 轮询3次获取认证字符串每次等待3秒
// var retryTimes = 3
// for i := 0; i < retryTimes; i++ {
// time.Sleep(time.Second * 3)
// token, err = GetAuth(a.cfg)
// if token != "" && err == nil {
// break
// }
// }
// // 如果最后获取到了token,执行token附加流程
// if token != "" {
// switch a.cfg.AuthPosition {
// case "header":
// ctx.Proxy().Header().SetHeader(a.cfg.AuthKey, token)
// case "body":
// if strings.Contains(strings.ToLower(ctx.Request().ContentType()), "application/json") {
// var body = make(map[string]interface{})
//
// bytes, err := ctx.Request().Body().RawBody()
// if err != nil {
// json.Unmarshal(bytes, &body)
// }
// body[a.Config.AuthKey] = token
// rebody, err := json.Marshal(body)
// if err != nil {
// ctx.Proxy().Body().SetRaw(ctx.Request().ContentType(), rebody)
// }
// } else {
// ctx.Proxy().Body().AddForm(a.cfg.AuthKey, token)
// }
// case "query":
// ctx.Proxy().URI().AddQuery(a.cfg.AuthKey, token)
// }
// }
//}

View File

@@ -0,0 +1,94 @@
package auth_interceptor
import (
"fmt"
"strings"
"github.com/eolinker/apinto/drivers"
"github.com/eolinker/eosc"
redis "github.com/redis/go-redis/v9"
)
const (
positionQuery = "query"
positionHeader = "header"
positionBody = "body"
)
// Config 参数配置属性
type Config struct {
SysKey string `json:"sys_key" label:"认证系统在Redis存储中的KEY值"`
AuthKey string `json:"auth_key" label:"认证参数KEY名"`
AuthPosition string `json:"auth_position" enum:"header,query,body" label:"认证参数追加位置"`
RedisConfig *RedisConfig `json:"redis" label:"Redis连接配置"`
RedisConn string `json:"redis_conn" label:"Redis连接名称"`
RetryCount int `json:"retry_count" label:"认证失败重试次数"`
RetryPeriod int `json:"retry_period" label:"认证失败重试间隔"`
}
type RedisConfig struct {
Addr string `json:"addr" label:"Redis连接地址"`
Username string `json:"username" label:"Redis连接用户名"`
Password string `json:"password" label:"Redis连接密码"`
DB int `json:"db" label:"Redis db序号"`
Mode string `json:"mode" label:"Redis连接模式"`
}
// Create 初始化插件执行实例
func Create(id, name string, conf *Config, workers map[eosc.RequireId]eosc.IWorker) (eosc.IWorker, error) {
err := conf.doCheck()
if err != nil {
return nil, err
}
var client redis.UniversalClient
ok := redisPool.Use(conf.RedisConn)
if !ok {
client, err = initRedis(conf.RedisConfig)
if err != nil {
return nil, err
}
redisPool.Set(conf.RedisConn, client)
}
auth := Auth{
WorkerBase: drivers.Worker(id, name),
cfg: conf,
redisConn: conf.RedisConn,
}
return &auth, nil
}
func (c *Config) doCheck() error {
if c.SysKey == "" {
return fmt.Errorf("[plugin auth-interceptor config err] param sys_key must be not null")
}
c.AuthPosition = strings.ToLower(c.AuthPosition)
switch c.AuthPosition {
case positionQuery, positionHeader, positionBody:
default:
return fmt.Errorf(`[plugin auth-interceptor config err] param position must be in the set ["query","header",body]. err position: %s `, c.AuthPosition)
}
if c.AuthKey == "" {
return fmt.Errorf("[plugin auth-interceptor config err] param auth_key must be not null")
}
if c.RedisConn == "" {
return fmt.Errorf("[plugin auth-interceptor config err] param redis_conn must be not null")
}
if c.RedisConfig == nil || c.RedisConfig.Addr == "" {
return fmt.Errorf("[plugin auth-interceptor config err] param RedisAddress must be not null")
}
if c.RetryCount < 0 {
c.RetryCount = 0
}
if c.RetryPeriod < 1 {
c.RetryPeriod = 5
}
return nil
}

View File

@@ -0,0 +1,18 @@
package auth_interceptor
import (
"github.com/eolinker/apinto/drivers"
"github.com/eolinker/eosc"
)
const (
Name = "auth_interceptor_redis"
)
func Register(register eosc.IExtenderDriverRegister) {
register.RegisterExtenderDriver(Name, NewFactory())
}
func NewFactory() eosc.IExtenderDriverFactory {
return drivers.NewFactory(Create)
}

View File

@@ -0,0 +1,116 @@
package auth_interceptor
import (
"context"
"strings"
"sync/atomic"
"time"
"github.com/eolinker/eosc"
redis "github.com/redis/go-redis/v9"
)
var redisPool = &pool{
pool: eosc.BuildUntyped[string, *redisClient](),
}
type pool struct {
pool eosc.Untyped[string, *redisClient]
}
func (p *pool) Use(name string) bool {
_, ok := p.pool.Get(name)
if !ok {
return false
}
return true
}
func (p *pool) Get(name string) redis.UniversalClient {
client, ok := p.pool.Get(name)
if !ok {
return nil
}
return client.Get()
}
func (p *pool) Set(name string, client redis.UniversalClient) {
c, ok := p.pool.Get(name)
if !ok {
c = &redisClient{
use: 1,
}
}
c.client = client
p.pool.Set(name, c)
}
func (p *pool) Release(name string) {
client, ok := p.pool.Get(name)
if !ok {
return
}
if client.Release() == 0 {
client.Close()
p.pool.Del(name)
}
}
type redisClient struct {
client redis.UniversalClient
use int32
}
func (r *redisClient) Use() {
atomic.AddInt32(&r.use, 1)
return
}
func (r *redisClient) Get() redis.UniversalClient {
return r.client
}
func (r *redisClient) Set(client redis.UniversalClient) {
r.client = client
}
func (r *redisClient) Release() int32 {
n := atomic.AddInt32(&r.use, -1)
return n
}
func (r *redisClient) Close() {
if r.client == nil {
return
}
r.client.Close()
r.client = nil
}
func initRedis(cfg *RedisConfig) (redis.UniversalClient, error) {
var client redis.UniversalClient
switch cfg.Mode {
case "cluster":
client = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: strings.Split(cfg.Addr, ","),
Username: cfg.Username,
Password: cfg.Password,
})
default:
client = redis.NewClient(&redis.Options{
Addr: cfg.Addr,
Username: cfg.Username,
Password: cfg.Password,
DB: cfg.DB,
})
}
timeout, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFunc()
if err := client.Ping(timeout).Err(); err != nil {
_ = client.Close()
return nil, err
}
return client, nil
}

View File

@@ -0,0 +1,46 @@
package params_check
import (
"testing"
"github.com/ohler55/ojg/oj"
"github.com/eolinker/apinto/checker"
)
func TestParamCheck(t *testing.T) {
data := `{
"code":"HWJXH_DEPTCOMPLEX_CSGLJ_HWJXHXT_XLJXHZYL_1.0",
"isPage":true,
"index":1,
"size":10,
"apiType":"deptCOMPLEX",
"userName":"APIFXJCXT",
"psd":"5190649892064f8c9bf387c3d30ce021",
"apiId":"d1d3f080f18448fcb5354f67b93e54e9",
"search":[{"param":"F_SECTIONNAME","type":"String","val":""}]
}`
c, err := checker.Parse("**")
if err != nil {
t.Fatal(err)
}
checkers := []*paramChecker{
{
name: "$.search[0].val",
Checker: c,
},
}
o, err := oj.ParseString(data)
if err != nil {
t.Fatal(err)
}
for _, ck := range checkers {
err = jsonChecker(o, ck)
if err != nil {
t.Fatal(err)
}
}
}

View File

@@ -0,0 +1,48 @@
package script_handler
import (
"fmt"
"github.com/eolinker/apinto/drivers"
"github.com/eolinker/eosc"
)
// 参数配置属性
type Config struct {
Script string `json:"script" label:"调用的脚本"`
Package string `json:"package" label:"调用的包名"`
Fname string `json:"fname" label:"调用函数名,需定义时返回error"`
Stage string `json:"stage" label:"脚本执行阶段request或response,默认request"`
}
// 初始化插件执行实例
func Create(id, name string, conf *Config, workers map[eosc.RequireId]eosc.IWorker) (eosc.IWorker, error) {
err := conf.doCheck()
if err != nil {
return nil, err
}
fn, err := getFunc(conf)
if err != nil {
return nil, err
}
return &Script{
WorkerBase: drivers.Worker(id, name),
stage: conf.Stage,
fn: fn,
}, nil
}
func (c *Config) doCheck() error {
if c.Script == "" {
return fmt.Errorf("[plugin script-handler config err] param Script must be not null")
}
if c.Package == "" {
return fmt.Errorf("[plugin script-handler config err] param Package must be not null")
}
if c.Fname == "" {
return fmt.Errorf("[plugin script-handler config err] param Fname must be not null")
}
return nil
}

View File

@@ -0,0 +1,18 @@
package script_handler
import (
"github.com/eolinker/apinto/drivers"
"github.com/eolinker/eosc"
)
const (
Name = "script_handler"
)
func Register(register eosc.IExtenderDriverRegister) {
register.RegisterExtenderDriver(Name, NewFactory())
}
func NewFactory() eosc.IExtenderDriverFactory {
return drivers.NewFactory(Create)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,325 @@
// Code generated by 'yaegi extract github.com/eolinker/eosc/eocontext'. DO NOT EDIT.
package script_handler
import (
"context"
"net"
"reflect"
"time"
"github.com/eolinker/eosc/eocontext"
"github.com/traefik/yaegi/stdlib"
)
func init() {
stdlib.Symbols["github.com/eolinker/eosc/eocontext/eocontext"] = map[string]reflect.Value{
// function, constant and variable definitions
"DoChain": reflect.ValueOf(eocontext.DoChain),
"Down": reflect.ValueOf(eocontext.Down),
"ErrEoCtxUnCloneable": reflect.ValueOf(&eocontext.ErrEoCtxUnCloneable).Elem(),
"FilterSkillName": reflect.ValueOf(&eocontext.FilterSkillName).Elem(),
"Leave": reflect.ValueOf(eocontext.Leave),
"NodeHost": reflect.ValueOf(eocontext.NodeHost),
"PassHost": reflect.ValueOf(eocontext.PassHost),
"ReWriteHost": reflect.ValueOf(eocontext.ReWriteHost),
"Running": reflect.ValueOf(eocontext.Running),
"ToFilter": reflect.ValueOf(eocontext.ToFilter),
// type definitions
"Attrs": reflect.ValueOf((*eocontext.Attrs)(nil)),
"BalanceHandler": reflect.ValueOf((*eocontext.BalanceHandler)(nil)),
"CompleteHandler": reflect.ValueOf((*eocontext.CompleteHandler)(nil)),
"EoApp": reflect.ValueOf((*eocontext.EoApp)(nil)),
"EoContext": reflect.ValueOf((*eocontext.EoContext)(nil)),
"Filters": reflect.ValueOf((*eocontext.Filters)(nil)),
"FinishHandler": reflect.ValueOf((*eocontext.FinishHandler)(nil)),
"IAttributes": reflect.ValueOf((*eocontext.IAttributes)(nil)),
"IChain": reflect.ValueOf((*eocontext.IChain)(nil)),
"IChainPro": reflect.ValueOf((*eocontext.IChainPro)(nil)),
"IFilter": reflect.ValueOf((*eocontext.IFilter)(nil)),
"INode": reflect.ValueOf((*eocontext.INode)(nil)),
"NodeStatus": reflect.ValueOf((*eocontext.NodeStatus)(nil)),
"PassHostMod": reflect.ValueOf((*eocontext.PassHostMod)(nil)),
"UpstreamHostHandler": reflect.ValueOf((*eocontext.UpstreamHostHandler)(nil)),
// interface wrapper definitions
"_BalanceHandler": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_BalanceHandler)(nil)),
"_CompleteHandler": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_CompleteHandler)(nil)),
"_EoApp": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_EoApp)(nil)),
"_EoContext": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_EoContext)(nil)),
"_FinishHandler": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_FinishHandler)(nil)),
"_IAttributes": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_IAttributes)(nil)),
"_IChain": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_IChain)(nil)),
"_IChainPro": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_IChainPro)(nil)),
"_IFilter": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_IFilter)(nil)),
"_INode": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_INode)(nil)),
"_UpstreamHostHandler": reflect.ValueOf((*_github_com_eolinker_eosc_eocontext_UpstreamHostHandler)(nil)),
}
}
// _github_com_eolinker_eosc_eocontext_BalanceHandler is an interface wrapper for BalanceHandler type
type _github_com_eolinker_eosc_eocontext_BalanceHandler struct {
IValue interface{}
WNodes func() []eocontext.INode
WScheme func() string
WSelect func(ctx eocontext.EoContext) (eocontext.INode, int, error)
WTimeOut func() time.Duration
}
func (W _github_com_eolinker_eosc_eocontext_BalanceHandler) Nodes() []eocontext.INode {
return W.WNodes()
}
func (W _github_com_eolinker_eosc_eocontext_BalanceHandler) Scheme() string {
return W.WScheme()
}
func (W _github_com_eolinker_eosc_eocontext_BalanceHandler) Select(ctx eocontext.EoContext) (eocontext.INode, int, error) {
return W.WSelect(ctx)
}
func (W _github_com_eolinker_eosc_eocontext_BalanceHandler) TimeOut() time.Duration {
return W.WTimeOut()
}
// _github_com_eolinker_eosc_eocontext_CompleteHandler is an interface wrapper for CompleteHandler type
type _github_com_eolinker_eosc_eocontext_CompleteHandler struct {
IValue interface{}
WComplete func(ctx eocontext.EoContext) error
}
func (W _github_com_eolinker_eosc_eocontext_CompleteHandler) Complete(ctx eocontext.EoContext) error {
return W.WComplete(ctx)
}
// _github_com_eolinker_eosc_eocontext_EoApp is an interface wrapper for EoApp type
type _github_com_eolinker_eosc_eocontext_EoApp struct {
IValue interface{}
WNodes func() []eocontext.INode
}
func (W _github_com_eolinker_eosc_eocontext_EoApp) Nodes() []eocontext.INode {
return W.WNodes()
}
// _github_com_eolinker_eosc_eocontext_EoContext is an interface wrapper for EoContext type
type _github_com_eolinker_eosc_eocontext_EoContext struct {
IValue interface{}
WAcceptTime func() time.Time
WAssert func(i interface{}) error
WClone func() (eocontext.EoContext, error)
WContext func() context.Context
WGetBalance func() eocontext.BalanceHandler
WGetComplete func() eocontext.CompleteHandler
WGetFinish func() eocontext.FinishHandler
WGetLabel func(name string) string
WGetUpstreamHostHandler func() eocontext.UpstreamHostHandler
WIsCloneable func() bool
WLabels func() map[string]string
WLocalAddr func() net.Addr
WLocalIP func() net.IP
WLocalPort func() int
WRealIP func() string
WRequestId func() string
WScheme func() string
WSetBalance func(handler eocontext.BalanceHandler)
WSetCompleteHandler func(handler eocontext.CompleteHandler)
WSetFinish func(handler eocontext.FinishHandler)
WSetLabel func(name string, value string)
WSetUpstreamHostHandler func(handler eocontext.UpstreamHostHandler)
WValue func(key interface{}) interface{}
WWithValue func(key interface{}, val interface{})
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) AcceptTime() time.Time {
return W.WAcceptTime()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) Assert(i interface{}) error {
return W.WAssert(i)
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) Clone() (eocontext.EoContext, error) {
return W.WClone()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) Context() context.Context {
return W.WContext()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) GetBalance() eocontext.BalanceHandler {
return W.WGetBalance()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) GetComplete() eocontext.CompleteHandler {
return W.WGetComplete()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) GetFinish() eocontext.FinishHandler {
return W.WGetFinish()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) GetLabel(name string) string {
return W.WGetLabel(name)
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) GetUpstreamHostHandler() eocontext.UpstreamHostHandler {
return W.WGetUpstreamHostHandler()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) IsCloneable() bool {
return W.WIsCloneable()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) Labels() map[string]string {
return W.WLabels()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) LocalAddr() net.Addr {
return W.WLocalAddr()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) LocalIP() net.IP {
return W.WLocalIP()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) LocalPort() int {
return W.WLocalPort()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) RealIP() string {
return W.WRealIP()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) RequestId() string {
return W.WRequestId()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) Scheme() string {
return W.WScheme()
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) SetBalance(handler eocontext.BalanceHandler) {
W.WSetBalance(handler)
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) SetCompleteHandler(handler eocontext.CompleteHandler) {
W.WSetCompleteHandler(handler)
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) SetFinish(handler eocontext.FinishHandler) {
W.WSetFinish(handler)
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) SetLabel(name string, value string) {
W.WSetLabel(name, value)
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) SetUpstreamHostHandler(handler eocontext.UpstreamHostHandler) {
W.WSetUpstreamHostHandler(handler)
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) Value(key interface{}) interface{} {
return W.WValue(key)
}
func (W _github_com_eolinker_eosc_eocontext_EoContext) WithValue(key interface{}, val interface{}) {
W.WWithValue(key, val)
}
// _github_com_eolinker_eosc_eocontext_FinishHandler is an interface wrapper for FinishHandler type
type _github_com_eolinker_eosc_eocontext_FinishHandler struct {
IValue interface{}
WFinish func(ctx eocontext.EoContext) error
}
func (W _github_com_eolinker_eosc_eocontext_FinishHandler) Finish(ctx eocontext.EoContext) error {
return W.WFinish(ctx)
}
// _github_com_eolinker_eosc_eocontext_IAttributes is an interface wrapper for IAttributes type
type _github_com_eolinker_eosc_eocontext_IAttributes struct {
IValue interface{}
WGetAttrByName func(name string) (string, bool)
WGetAttrs func() eocontext.Attrs
}
func (W _github_com_eolinker_eosc_eocontext_IAttributes) GetAttrByName(name string) (string, bool) {
return W.WGetAttrByName(name)
}
func (W _github_com_eolinker_eosc_eocontext_IAttributes) GetAttrs() eocontext.Attrs {
return W.WGetAttrs()
}
// _github_com_eolinker_eosc_eocontext_IChain is an interface wrapper for IChain type
type _github_com_eolinker_eosc_eocontext_IChain struct {
IValue interface{}
WDestroy func()
WDoChain func(ctx eocontext.EoContext) error
}
func (W _github_com_eolinker_eosc_eocontext_IChain) Destroy() {
W.WDestroy()
}
func (W _github_com_eolinker_eosc_eocontext_IChain) DoChain(ctx eocontext.EoContext) error {
return W.WDoChain(ctx)
}
// _github_com_eolinker_eosc_eocontext_IChainPro is an interface wrapper for IChainPro type
type _github_com_eolinker_eosc_eocontext_IChainPro struct {
IValue interface{}
WChain func(ctx eocontext.EoContext, append ...eocontext.IFilter) error
WDestroy func()
}
func (W _github_com_eolinker_eosc_eocontext_IChainPro) Chain(ctx eocontext.EoContext, append ...eocontext.IFilter) error {
return W.WChain(ctx, append...)
}
func (W _github_com_eolinker_eosc_eocontext_IChainPro) Destroy() {
W.WDestroy()
}
// _github_com_eolinker_eosc_eocontext_IFilter is an interface wrapper for IFilter type
type _github_com_eolinker_eosc_eocontext_IFilter struct {
IValue interface{}
WDestroy func()
WDoFilter func(ctx eocontext.EoContext, next eocontext.IChain) (err error)
}
func (W _github_com_eolinker_eosc_eocontext_IFilter) Destroy() {
W.WDestroy()
}
func (W _github_com_eolinker_eosc_eocontext_IFilter) DoFilter(ctx eocontext.EoContext, next eocontext.IChain) (err error) {
return W.WDoFilter(ctx, next)
}
// _github_com_eolinker_eosc_eocontext_INode is an interface wrapper for INode type
type _github_com_eolinker_eosc_eocontext_INode struct {
IValue interface{}
WAddr func() string
WDown func()
WGetAttrByName func(name string) (string, bool)
WGetAttrs func() eocontext.Attrs
WID func() string
WIP func() string
WLeave func()
WPort func() int
WStatus func() eocontext.NodeStatus
WUp func()
}
func (W _github_com_eolinker_eosc_eocontext_INode) Addr() string {
return W.WAddr()
}
func (W _github_com_eolinker_eosc_eocontext_INode) Down() {
W.WDown()
}
func (W _github_com_eolinker_eosc_eocontext_INode) GetAttrByName(name string) (string, bool) {
return W.WGetAttrByName(name)
}
func (W _github_com_eolinker_eosc_eocontext_INode) GetAttrs() eocontext.Attrs {
return W.WGetAttrs()
}
func (W _github_com_eolinker_eosc_eocontext_INode) ID() string {
return W.WID()
}
func (W _github_com_eolinker_eosc_eocontext_INode) IP() string {
return W.WIP()
}
func (W _github_com_eolinker_eosc_eocontext_INode) Leave() {
W.WLeave()
}
func (W _github_com_eolinker_eosc_eocontext_INode) Port() int {
return W.WPort()
}
func (W _github_com_eolinker_eosc_eocontext_INode) Status() eocontext.NodeStatus {
return W.WStatus()
}
func (W _github_com_eolinker_eosc_eocontext_INode) Up() {
W.WUp()
}
// _github_com_eolinker_eosc_eocontext_UpstreamHostHandler is an interface wrapper for UpstreamHostHandler type
type _github_com_eolinker_eosc_eocontext_UpstreamHostHandler struct {
IValue interface{}
WPassHost func() (eocontext.PassHostMod, string)
}
func (W _github_com_eolinker_eosc_eocontext_UpstreamHostHandler) PassHost() (eocontext.PassHostMod, string) {
return W.WPassHost()
}

View File

@@ -0,0 +1,518 @@
// Code generated by 'yaegi extract github.com/eolinker/eosc'. DO NOT EDIT.
package script_handler
import (
"go/constant"
"go/token"
"os"
"reflect"
"github.com/eolinker/eosc"
"github.com/traefik/yaegi/stdlib"
)
func init() {
stdlib.Symbols["github.com/eolinker/eosc/eosc"] = map[string]reflect.Value{
// function, constant and variable definitions
"ErrorConfigFieldUnknown": reflect.ValueOf(&eosc.ErrorConfigFieldUnknown).Elem(),
"ErrorConfigIsNil": reflect.ValueOf(&eosc.ErrorConfigIsNil).Elem(),
"ErrorConfigType": reflect.ValueOf(&eosc.ErrorConfigType).Elem(),
"ErrorDriverNotExist": reflect.ValueOf(&eosc.ErrorDriverNotExist).Elem(),
"ErrorDriverNotMatch": reflect.ValueOf(&eosc.ErrorDriverNotMatch).Elem(),
"ErrorNotAllowCreateForSingleton": reflect.ValueOf(&eosc.ErrorNotAllowCreateForSingleton).Elem(),
"ErrorNotGetSillForRequire": reflect.ValueOf(&eosc.ErrorNotGetSillForRequire).Elem(),
"ErrorParamNotExist": reflect.ValueOf(&eosc.ErrorParamNotExist).Elem(),
"ErrorParamsIsNil": reflect.ValueOf(&eosc.ErrorParamsIsNil).Elem(),
"ErrorProfessionDependencies": reflect.ValueOf(&eosc.ErrorProfessionDependencies).Elem(),
"ErrorProfessionNotExist": reflect.ValueOf(&eosc.ErrorProfessionNotExist).Elem(),
"ErrorProfessionNotMatch": reflect.ValueOf(&eosc.ErrorProfessionNotMatch).Elem(),
"ErrorRegisterConflict": reflect.ValueOf(&eosc.ErrorRegisterConflict).Elem(),
"ErrorRequire": reflect.ValueOf(&eosc.ErrorRequire).Elem(),
"ErrorStoreReadOnly": reflect.ValueOf(&eosc.ErrorStoreReadOnly).Elem(),
"ErrorTargetNotImplementSkill": reflect.ValueOf(&eosc.ErrorTargetNotImplementSkill).Elem(),
"ErrorUnsupportedKind": reflect.ValueOf(&eosc.ErrorUnsupportedKind).Elem(),
"ErrorWorkerNotExits": reflect.ValueOf(&eosc.ErrorWorkerNotExits).Elem(),
"ErrorWorkerNotRunning": reflect.ValueOf(&eosc.ErrorWorkerNotRunning).Elem(),
"EventDel": reflect.ValueOf(constant.MakeFromLiteral("\"delete\"", token.STRING, 0)),
"EventInit": reflect.ValueOf(constant.MakeFromLiteral("\"init\"", token.STRING, 0)),
"EventReset": reflect.ValueOf(constant.MakeFromLiteral("\"getFunc\"", token.STRING, 0)),
"EventSet": reflect.ValueOf(constant.MakeFromLiteral("\"set\"", token.STRING, 0)),
"File_message_proto": reflect.ValueOf(&eosc.File_message_proto).Elem(),
"NamespaceCustomer": reflect.ValueOf(constant.MakeFromLiteral("\"customer\"", token.STRING, 0)),
"NamespaceExtender": reflect.ValueOf(constant.MakeFromLiteral("\"extender\"", token.STRING, 0)),
"NamespaceProfession": reflect.ValueOf(constant.MakeFromLiteral("\"profession\"", token.STRING, 0)),
"NamespaceVariable": reflect.ValueOf(constant.MakeFromLiteral("\"variable\"", token.STRING, 0)),
"NamespaceWorker": reflect.ValueOf(constant.MakeFromLiteral("\"worker\"", token.STRING, 0)),
"NewExtenderRegister": reflect.ValueOf(eosc.NewExtenderRegister),
"Now": reflect.ValueOf(eosc.Now),
"ProcessAdmin": reflect.ValueOf(constant.MakeFromLiteral("\"admin\"", token.STRING, 0)),
"ProcessHelper": reflect.ValueOf(constant.MakeFromLiteral("\"helper\"", token.STRING, 0)),
"ProcessMaster": reflect.ValueOf(constant.MakeFromLiteral("\"master\"", token.STRING, 0)),
"ProcessWorker": reflect.ValueOf(constant.MakeFromLiteral("\"worker\"", token.STRING, 0)),
"ProfessionConfig_ProfessionMod_name": reflect.ValueOf(&eosc.ProfessionConfig_ProfessionMod_name).Elem(),
"ProfessionConfig_ProfessionMod_value": reflect.ValueOf(&eosc.ProfessionConfig_ProfessionMod_value).Elem(),
"ProfessionConfig_Singleton": reflect.ValueOf(eosc.ProfessionConfig_Singleton),
"ProfessionConfig_Worker": reflect.ValueOf(eosc.ProfessionConfig_Worker),
"ReadStringFromEntry": reflect.ValueOf(eosc.ReadStringFromEntry),
"SHA1": reflect.ValueOf(eosc.SHA1),
"SettingModeBatch": reflect.ValueOf(eosc.SettingModeBatch),
"SettingModeReadonly": reflect.ValueOf(eosc.SettingModeReadonly),
"SettingModeSingleton": reflect.ValueOf(eosc.SettingModeSingleton),
"SplitWorkerId": reflect.ValueOf(eosc.SplitWorkerId),
"String": reflect.ValueOf(eosc.String),
"ToWorkerId": reflect.ValueOf(eosc.ToWorkerId),
"Version": reflect.ValueOf(eosc.Version),
// type definitions
"DriverConfig": reflect.ValueOf((*eosc.DriverConfig)(nil)),
"EoFiles": reflect.ValueOf((*eosc.EoFiles)(nil)),
"ExtenderBuilder": reflect.ValueOf((*eosc.ExtenderBuilder)(nil)),
"ExtenderRegister": reflect.ValueOf((*eosc.ExtenderRegister)(nil)),
"ExtendersSettings": reflect.ValueOf((*eosc.ExtendersSettings)(nil)),
"FormatterConfig": reflect.ValueOf((*eosc.FormatterConfig)(nil)),
"GzipFile": reflect.ValueOf((*eosc.GzipFile)(nil)),
"ICustomerVar": reflect.ValueOf((*eosc.ICustomerVar)(nil)),
"IDataMarshaller": reflect.ValueOf((*eosc.IDataMarshaller)(nil)),
"IEntry": reflect.ValueOf((*eosc.IEntry)(nil)),
"IExtenderConfigChecker": reflect.ValueOf((*eosc.IExtenderConfigChecker)(nil)),
"IExtenderDriver": reflect.ValueOf((*eosc.IExtenderDriver)(nil)),
"IExtenderDriverFactory": reflect.ValueOf((*eosc.IExtenderDriverFactory)(nil)),
"IExtenderDriverManager": reflect.ValueOf((*eosc.IExtenderDriverManager)(nil)),
"IExtenderDriverRegister": reflect.ValueOf((*eosc.IExtenderDriverRegister)(nil)),
"IExtenderDrivers": reflect.ValueOf((*eosc.IExtenderDrivers)(nil)),
"IFormatter": reflect.ValueOf((*eosc.IFormatter)(nil)),
"IFormatterFactory": reflect.ValueOf((*eosc.IFormatterFactory)(nil)),
"IMetricEntry": reflect.ValueOf((*eosc.IMetricEntry)(nil)),
"IProfession": reflect.ValueOf((*eosc.IProfession)(nil)),
"IProfessions": reflect.ValueOf((*eosc.IProfessions)(nil)),
"IRequires": reflect.ValueOf((*eosc.IRequires)(nil)),
"ISetting": reflect.ValueOf((*eosc.ISetting)(nil)),
"ISettings": reflect.ValueOf((*eosc.ISettings)(nil)),
"IVariable": reflect.ValueOf((*eosc.IVariable)(nil)),
"IWorker": reflect.ValueOf((*eosc.IWorker)(nil)),
"IWorkerDestroy": reflect.ValueOf((*eosc.IWorkerDestroy)(nil)),
"IWorkers": reflect.ValueOf((*eosc.IWorkers)(nil)),
"Item": reflect.ValueOf((*eosc.Item)(nil)),
"ProcessStatus": reflect.ValueOf((*eosc.ProcessStatus)(nil)),
"ProfessionConfig": reflect.ValueOf((*eosc.ProfessionConfig)(nil)),
"ProfessionConfig_ProfessionMod": reflect.ValueOf((*eosc.ProfessionConfig_ProfessionMod)(nil)),
"ProfessionConfigs": reflect.ValueOf((*eosc.ProfessionConfigs)(nil)),
"RequireId": reflect.ValueOf((*eosc.RequireId)(nil)),
"SettingMode": reflect.ValueOf((*eosc.SettingMode)(nil)),
"TWorker": reflect.ValueOf((*eosc.TWorker)(nil)),
"WorkerConfig": reflect.ValueOf((*eosc.WorkerConfig)(nil)),
// interface wrapper definitions
"_ExtenderBuilder": reflect.ValueOf((*_github_com_eolinker_eosc_ExtenderBuilder)(nil)),
"_ICustomerVar": reflect.ValueOf((*_github_com_eolinker_eosc_ICustomerVar)(nil)),
"_IDataMarshaller": reflect.ValueOf((*_github_com_eolinker_eosc_IDataMarshaller)(nil)),
"_IEntry": reflect.ValueOf((*_github_com_eolinker_eosc_IEntry)(nil)),
"_IExtenderConfigChecker": reflect.ValueOf((*_github_com_eolinker_eosc_IExtenderConfigChecker)(nil)),
"_IExtenderDriver": reflect.ValueOf((*_github_com_eolinker_eosc_IExtenderDriver)(nil)),
"_IExtenderDriverFactory": reflect.ValueOf((*_github_com_eolinker_eosc_IExtenderDriverFactory)(nil)),
"_IExtenderDriverManager": reflect.ValueOf((*_github_com_eolinker_eosc_IExtenderDriverManager)(nil)),
"_IExtenderDriverRegister": reflect.ValueOf((*_github_com_eolinker_eosc_IExtenderDriverRegister)(nil)),
"_IExtenderDrivers": reflect.ValueOf((*_github_com_eolinker_eosc_IExtenderDrivers)(nil)),
"_IFormatter": reflect.ValueOf((*_github_com_eolinker_eosc_IFormatter)(nil)),
"_IFormatterFactory": reflect.ValueOf((*_github_com_eolinker_eosc_IFormatterFactory)(nil)),
"_IMetricEntry": reflect.ValueOf((*_github_com_eolinker_eosc_IMetricEntry)(nil)),
"_IProfession": reflect.ValueOf((*_github_com_eolinker_eosc_IProfession)(nil)),
"_IProfessions": reflect.ValueOf((*_github_com_eolinker_eosc_IProfessions)(nil)),
"_IRequires": reflect.ValueOf((*_github_com_eolinker_eosc_IRequires)(nil)),
"_ISetting": reflect.ValueOf((*_github_com_eolinker_eosc_ISetting)(nil)),
"_ISettings": reflect.ValueOf((*_github_com_eolinker_eosc_ISettings)(nil)),
"_IVariable": reflect.ValueOf((*_github_com_eolinker_eosc_IVariable)(nil)),
"_IWorker": reflect.ValueOf((*_github_com_eolinker_eosc_IWorker)(nil)),
"_IWorkerDestroy": reflect.ValueOf((*_github_com_eolinker_eosc_IWorkerDestroy)(nil)),
"_IWorkers": reflect.ValueOf((*_github_com_eolinker_eosc_IWorkers)(nil)),
}
}
// _github_com_eolinker_eosc_ExtenderBuilder is an interface wrapper for ExtenderBuilder type
type _github_com_eolinker_eosc_ExtenderBuilder struct {
IValue interface{}
WRegister func(register eosc.IExtenderDriverRegister)
}
func (W _github_com_eolinker_eosc_ExtenderBuilder) Register(register eosc.IExtenderDriverRegister) {
W.WRegister(register)
}
// _github_com_eolinker_eosc_ICustomerVar is an interface wrapper for ICustomerVar type
type _github_com_eolinker_eosc_ICustomerVar struct {
IValue interface{}
WExists func(key string, field string) bool
WGet func(key string, field string) (string, bool)
WGetAll func(key string) (map[string]string, bool)
}
func (W _github_com_eolinker_eosc_ICustomerVar) Exists(key string, field string) bool {
return W.WExists(key, field)
}
func (W _github_com_eolinker_eosc_ICustomerVar) Get(key string, field string) (string, bool) {
return W.WGet(key, field)
}
func (W _github_com_eolinker_eosc_ICustomerVar) GetAll(key string) (map[string]string, bool) {
return W.WGetAll(key)
}
// _github_com_eolinker_eosc_IDataMarshaller is an interface wrapper for IDataMarshaller type
type _github_com_eolinker_eosc_IDataMarshaller struct {
IValue interface{}
WEncode func(startIndex int) ([]byte, []*os.File, error)
}
func (W _github_com_eolinker_eosc_IDataMarshaller) Encode(startIndex int) ([]byte, []*os.File, error) {
return W.WEncode(startIndex)
}
// _github_com_eolinker_eosc_IEntry is an interface wrapper for IEntry type
type _github_com_eolinker_eosc_IEntry struct {
IValue interface{}
WChildren func(child string) []eosc.IEntry
WRead func(pattern string) interface{}
WReadLabel func(pattern string) string
}
func (W _github_com_eolinker_eosc_IEntry) Children(child string) []eosc.IEntry {
return W.WChildren(child)
}
func (W _github_com_eolinker_eosc_IEntry) Read(pattern string) interface{} {
return W.WRead(pattern)
}
func (W _github_com_eolinker_eosc_IEntry) ReadLabel(pattern string) string {
return W.WReadLabel(pattern)
}
// _github_com_eolinker_eosc_IExtenderConfigChecker is an interface wrapper for IExtenderConfigChecker type
type _github_com_eolinker_eosc_IExtenderConfigChecker struct {
IValue interface{}
WCheck func(v interface{}, workers map[eosc.RequireId]eosc.IWorker) error
}
func (W _github_com_eolinker_eosc_IExtenderConfigChecker) Check(v interface{}, workers map[eosc.RequireId]eosc.IWorker) error {
return W.WCheck(v, workers)
}
// _github_com_eolinker_eosc_IExtenderDriver is an interface wrapper for IExtenderDriver type
type _github_com_eolinker_eosc_IExtenderDriver struct {
IValue interface{}
WConfigType func() reflect.Type
WCreate func(id string, name string, v interface{}, workers map[eosc.RequireId]eosc.IWorker) (eosc.IWorker, error)
}
func (W _github_com_eolinker_eosc_IExtenderDriver) ConfigType() reflect.Type {
return W.WConfigType()
}
func (W _github_com_eolinker_eosc_IExtenderDriver) Create(id string, name string, v interface{}, workers map[eosc.RequireId]eosc.IWorker) (eosc.IWorker, error) {
return W.WCreate(id, name, v, workers)
}
// _github_com_eolinker_eosc_IExtenderDriverFactory is an interface wrapper for IExtenderDriverFactory type
type _github_com_eolinker_eosc_IExtenderDriverFactory struct {
IValue interface{}
WCreate func(profession string, name string, label string, desc string, params map[string]interface{}) (eosc.IExtenderDriver, error)
WRender func() interface{}
}
func (W _github_com_eolinker_eosc_IExtenderDriverFactory) Create(profession string, name string, label string, desc string, params map[string]interface{}) (eosc.IExtenderDriver, error) {
return W.WCreate(profession, name, label, desc, params)
}
func (W _github_com_eolinker_eosc_IExtenderDriverFactory) Render() interface{} {
return W.WRender()
}
// _github_com_eolinker_eosc_IExtenderDriverManager is an interface wrapper for IExtenderDriverManager type
type _github_com_eolinker_eosc_IExtenderDriverManager struct {
IValue interface{}
WRegisterExtenderDriver func(name string, factory eosc.IExtenderDriverFactory) error
}
func (W _github_com_eolinker_eosc_IExtenderDriverManager) RegisterExtenderDriver(name string, factory eosc.IExtenderDriverFactory) error {
return W.WRegisterExtenderDriver(name, factory)
}
// _github_com_eolinker_eosc_IExtenderDriverRegister is an interface wrapper for IExtenderDriverRegister type
type _github_com_eolinker_eosc_IExtenderDriverRegister struct {
IValue interface{}
WRegisterExtenderDriver func(name string, factory eosc.IExtenderDriverFactory) error
}
func (W _github_com_eolinker_eosc_IExtenderDriverRegister) RegisterExtenderDriver(name string, factory eosc.IExtenderDriverFactory) error {
return W.WRegisterExtenderDriver(name, factory)
}
// _github_com_eolinker_eosc_IExtenderDrivers is an interface wrapper for IExtenderDrivers type
type _github_com_eolinker_eosc_IExtenderDrivers struct {
IValue interface{}
WGetDriver func(name string) (eosc.IExtenderDriverFactory, bool)
}
func (W _github_com_eolinker_eosc_IExtenderDrivers) GetDriver(name string) (eosc.IExtenderDriverFactory, bool) {
return W.WGetDriver(name)
}
// _github_com_eolinker_eosc_IFormatter is an interface wrapper for IFormatter type
type _github_com_eolinker_eosc_IFormatter struct {
IValue interface{}
WFormat func(entry eosc.IEntry) []byte
}
func (W _github_com_eolinker_eosc_IFormatter) Format(entry eosc.IEntry) []byte {
return W.WFormat(entry)
}
// _github_com_eolinker_eosc_IFormatterFactory is an interface wrapper for IFormatterFactory type
type _github_com_eolinker_eosc_IFormatterFactory struct {
IValue interface{}
WCreate func(cfg eosc.FormatterConfig, extendCfg ...interface{}) (eosc.IFormatter, error)
}
func (W _github_com_eolinker_eosc_IFormatterFactory) Create(cfg eosc.FormatterConfig, extendCfg ...interface{}) (eosc.IFormatter, error) {
return W.WCreate(cfg, extendCfg...)
}
// _github_com_eolinker_eosc_IMetricEntry is an interface wrapper for IMetricEntry type
type _github_com_eolinker_eosc_IMetricEntry struct {
IValue interface{}
WChildren func(child string) []eosc.IMetricEntry
WGetFloat func(pattern string) (float64, bool)
WRead func(pattern string) string
}
func (W _github_com_eolinker_eosc_IMetricEntry) Children(child string) []eosc.IMetricEntry {
return W.WChildren(child)
}
func (W _github_com_eolinker_eosc_IMetricEntry) GetFloat(pattern string) (float64, bool) {
return W.WGetFloat(pattern)
}
func (W _github_com_eolinker_eosc_IMetricEntry) Read(pattern string) string {
return W.WRead(pattern)
}
// _github_com_eolinker_eosc_IProfession is an interface wrapper for IProfession type
type _github_com_eolinker_eosc_IProfession struct {
IValue interface{}
WAppendAttr func() []string
WDrivers func() []*eosc.DriverConfig
WGetDriver func(name string) (*eosc.DriverConfig, bool)
WHasDriver func(name string) bool
WMod func() eosc.ProfessionConfig_ProfessionMod
}
func (W _github_com_eolinker_eosc_IProfession) AppendAttr() []string {
return W.WAppendAttr()
}
func (W _github_com_eolinker_eosc_IProfession) Drivers() []*eosc.DriverConfig {
return W.WDrivers()
}
func (W _github_com_eolinker_eosc_IProfession) GetDriver(name string) (*eosc.DriverConfig, bool) {
return W.WGetDriver(name)
}
func (W _github_com_eolinker_eosc_IProfession) HasDriver(name string) bool {
return W.WHasDriver(name)
}
func (W _github_com_eolinker_eosc_IProfession) Mod() eosc.ProfessionConfig_ProfessionMod {
return W.WMod()
}
// _github_com_eolinker_eosc_IProfessions is an interface wrapper for IProfessions type
type _github_com_eolinker_eosc_IProfessions struct {
IValue interface{}
WAll func() []*eosc.ProfessionConfig
WDelete func(name string) error
WGetProfession func(name string) (eosc.IProfession, bool)
WNames func() []string
WReset func(a0 []*eosc.ProfessionConfig)
WSet func(name string, profession *eosc.ProfessionConfig) error
}
func (W _github_com_eolinker_eosc_IProfessions) All() []*eosc.ProfessionConfig {
return W.WAll()
}
func (W _github_com_eolinker_eosc_IProfessions) Delete(name string) error {
return W.WDelete(name)
}
func (W _github_com_eolinker_eosc_IProfessions) GetProfession(name string) (eosc.IProfession, bool) {
return W.WGetProfession(name)
}
func (W _github_com_eolinker_eosc_IProfessions) Names() []string {
return W.WNames()
}
func (W _github_com_eolinker_eosc_IProfessions) Reset(a0 []*eosc.ProfessionConfig) {
W.WReset(a0)
}
func (W _github_com_eolinker_eosc_IProfessions) Set(name string, profession *eosc.ProfessionConfig) error {
return W.WSet(name, profession)
}
// _github_com_eolinker_eosc_IRequires is an interface wrapper for IRequires type
type _github_com_eolinker_eosc_IRequires struct {
IValue interface{}
WDel func(id string)
WRequireBy func(requireId string) []string
WRequireByCount func(requireId string) int
WRequires func(id string) []string
WSet func(id string, requires []string)
}
func (W _github_com_eolinker_eosc_IRequires) Del(id string) {
W.WDel(id)
}
func (W _github_com_eolinker_eosc_IRequires) RequireBy(requireId string) []string {
return W.WRequireBy(requireId)
}
func (W _github_com_eolinker_eosc_IRequires) RequireByCount(requireId string) int {
return W.WRequireByCount(requireId)
}
func (W _github_com_eolinker_eosc_IRequires) Requires(id string) []string {
return W.WRequires(id)
}
func (W _github_com_eolinker_eosc_IRequires) Set(id string, requires []string) {
W.WSet(id, requires)
}
// _github_com_eolinker_eosc_ISetting is an interface wrapper for ISetting type
type _github_com_eolinker_eosc_ISetting struct {
IValue interface{}
WAllWorkers func() []string
WCheck func(cfg interface{}) (profession string, name string, driver string, desc string, err error)
WConfigType func() reflect.Type
WGet func() interface{}
WMode func() eosc.SettingMode
WSet func(conf interface{}) (err error)
}
func (W _github_com_eolinker_eosc_ISetting) AllWorkers() []string {
return W.WAllWorkers()
}
func (W _github_com_eolinker_eosc_ISetting) Check(cfg interface{}) (profession string, name string, driver string, desc string, err error) {
return W.WCheck(cfg)
}
func (W _github_com_eolinker_eosc_ISetting) ConfigType() reflect.Type {
return W.WConfigType()
}
func (W _github_com_eolinker_eosc_ISetting) Get() interface{} {
return W.WGet()
}
func (W _github_com_eolinker_eosc_ISetting) Mode() eosc.SettingMode {
return W.WMode()
}
func (W _github_com_eolinker_eosc_ISetting) Set(conf interface{}) (err error) {
return W.WSet(conf)
}
// _github_com_eolinker_eosc_ISettings is an interface wrapper for ISettings type
type _github_com_eolinker_eosc_ISettings struct {
IValue interface{}
WCheckVariable func(name string) (err error)
WGetConfig func(name string) interface{}
WGetConfigBody func(name string) ([]byte, bool)
WGetDriver func(name string) (eosc.ISetting, bool)
WSettingWorker func(name string, config []byte) error
WUpdate func(name string) (err error)
}
func (W _github_com_eolinker_eosc_ISettings) CheckVariable(name string) (err error) {
return W.WCheckVariable(name)
}
func (W _github_com_eolinker_eosc_ISettings) GetConfig(name string) interface{} {
return W.WGetConfig(name)
}
func (W _github_com_eolinker_eosc_ISettings) GetConfigBody(name string) ([]byte, bool) {
return W.WGetConfigBody(name)
}
func (W _github_com_eolinker_eosc_ISettings) GetDriver(name string) (eosc.ISetting, bool) {
return W.WGetDriver(name)
}
func (W _github_com_eolinker_eosc_ISettings) SettingWorker(name string, config []byte) error {
return W.WSettingWorker(name, config)
}
func (W _github_com_eolinker_eosc_ISettings) Update(name string) (err error) {
return W.WUpdate(name)
}
// _github_com_eolinker_eosc_IVariable is an interface wrapper for IVariable type
type _github_com_eolinker_eosc_IVariable struct {
IValue interface{}
WAll func() map[string]map[string]string
WGet func(id string) (string, bool)
WGetByNamespace func(namespace string) (map[string]string, bool)
WLen func() int
WRemoveRequire func(id string)
WSetByNamespace func(namespace string, variables map[string]string) (affectIds []string, clone map[string]string, err error)
WSetRequire func(id string, variables []string)
WUnmarshal func(buf []byte, typ reflect.Type) (interface{}, []string, error)
}
func (W _github_com_eolinker_eosc_IVariable) All() map[string]map[string]string {
return W.WAll()
}
func (W _github_com_eolinker_eosc_IVariable) Get(id string) (string, bool) {
return W.WGet(id)
}
func (W _github_com_eolinker_eosc_IVariable) GetByNamespace(namespace string) (map[string]string, bool) {
return W.WGetByNamespace(namespace)
}
func (W _github_com_eolinker_eosc_IVariable) Len() int {
return W.WLen()
}
func (W _github_com_eolinker_eosc_IVariable) RemoveRequire(id string) {
W.WRemoveRequire(id)
}
func (W _github_com_eolinker_eosc_IVariable) SetByNamespace(namespace string, variables map[string]string) (affectIds []string, clone map[string]string, err error) {
return W.WSetByNamespace(namespace, variables)
}
func (W _github_com_eolinker_eosc_IVariable) SetRequire(id string, variables []string) {
W.WSetRequire(id, variables)
}
func (W _github_com_eolinker_eosc_IVariable) Unmarshal(buf []byte, typ reflect.Type) (interface{}, []string, error) {
return W.WUnmarshal(buf, typ)
}
// _github_com_eolinker_eosc_IWorker is an interface wrapper for IWorker type
type _github_com_eolinker_eosc_IWorker struct {
IValue interface{}
WCheckSkill func(skill string) bool
WId func() string
WReset func(conf interface{}, workers map[eosc.RequireId]eosc.IWorker) error
WStart func() error
WStop func() error
}
func (W _github_com_eolinker_eosc_IWorker) CheckSkill(skill string) bool {
return W.WCheckSkill(skill)
}
func (W _github_com_eolinker_eosc_IWorker) Id() string {
return W.WId()
}
func (W _github_com_eolinker_eosc_IWorker) Reset(conf interface{}, workers map[eosc.RequireId]eosc.IWorker) error {
return W.WReset(conf, workers)
}
func (W _github_com_eolinker_eosc_IWorker) Start() error {
return W.WStart()
}
func (W _github_com_eolinker_eosc_IWorker) Stop() error {
return W.WStop()
}
// _github_com_eolinker_eosc_IWorkerDestroy is an interface wrapper for IWorkerDestroy type
type _github_com_eolinker_eosc_IWorkerDestroy struct {
IValue interface{}
WDestroy func() error
}
func (W _github_com_eolinker_eosc_IWorkerDestroy) Destroy() error {
return W.WDestroy()
}
// _github_com_eolinker_eosc_IWorkers is an interface wrapper for IWorkers type
type _github_com_eolinker_eosc_IWorkers struct {
IValue interface{}
WGet func(id string) (eosc.IWorker, bool)
}
func (W _github_com_eolinker_eosc_IWorkers) Get(id string) (eosc.IWorker, bool) {
return W.WGet(id)
}

View File

@@ -0,0 +1,102 @@
package script_handler
import (
"fmt"
"github.com/eolinker/eosc/log"
"github.com/eolinker/apinto/drivers"
"github.com/eolinker/eosc"
"github.com/eolinker/eosc/eocontext"
http_service "github.com/eolinker/eosc/eocontext/http-context"
"github.com/traefik/yaegi/interp"
"github.com/traefik/yaegi/stdlib"
)
type Script struct {
drivers.WorkerBase
stage string
fn func(ctx http_service.IHttpContext) error
}
func (a *Script) Destroy() {
a.fn = nil
return
}
// 拦截请求过滤内部转换为http类型再处理
func (a *Script) DoFilter(ctx eocontext.EoContext, next eocontext.IChain) (err error) {
return http_service.DoHttpFilter(a, ctx, next)
}
// 插件添加时执行
func (a *Script) Start() error {
return nil
}
// 插件被修改时执行
func (a *Script) Reset(conf interface{}, workers map[eosc.RequireId]eosc.IWorker) error {
return nil
}
func getFunc(conf *Config) (func(http_service.IHttpContext) error, error) {
err := conf.doCheck()
if err != nil {
return nil, err
}
i := interp.New(interp.Options{})
err = i.Use(stdlib.Symbols)
if err != nil {
return nil, err
}
_, err = i.Eval(conf.Script)
if err != nil {
return nil, err
}
v, err := i.Eval(conf.Package + "." + conf.Fname)
if err != nil {
return nil, err
}
fn, ok := v.Interface().(func(http_service.IHttpContext) error)
if !ok {
return nil, fmt.Errorf("invalid function")
}
return fn, nil
}
// 插件删除时间执行
func (a *Script) Stop() error {
return nil
}
func (a *Script) CheckSkill(skill string) bool {
return http_service.FilterSkillName == skill
}
// DoHttpFilter 核心http处理方法
func (a *Script) DoHttpFilter(ctx http_service.IHttpContext, next eocontext.IChain) error {
defer func() {
err := recover()
if err != nil {
log.Errorf("script invoke error: %v", err)
}
}()
if a.stage == "" || a.stage == "request" {
err := a.fn(ctx)
if err != nil {
log.Errorf("exec request script error: %s", err.Error())
return err
}
}
err := next.DoChain(ctx)
if err != nil {
err := a.fn(ctx)
if err != nil {
log.Errorf("exec response script error: %s", err.Error())
return err
}
}
return nil
}

View File

@@ -0,0 +1,282 @@
package script_handler
import (
"context"
"net"
"testing"
"time"
"github.com/eolinker/apinto/drivers"
http_context "github.com/eolinker/eosc/eocontext/http-context"
"github.com/eolinker/eosc"
"github.com/eolinker/eosc/eocontext"
)
var scriptEaxample = `
package test
import (
"fmt"
"github.com/eolinker/eosc/eocontext"
http_service "github.com/eolinker/eosc/eocontext/http-context"
)
func RenameHost(ctx http_service.IHttpContext) error{
println("test script")
panic("test")
return fmt.Errorf("test error")
ctx.Proxy().URI().SetHost("http://testUri.com")
}
`
func TestScript(t *testing.T) {
var config = &Config{
Script: scriptEaxample,
Package: "test",
Fname: "RenameHost",
}
fn, err := getFunc(config)
if err != nil {
t.Fatal(err)
}
var script = Script{
Config: config,
WorkerBase: drivers.Worker("test", "test"),
fn: fn,
}
err = script.DoHttpFilter(HttpContext{}, MockChain{})
if err != nil {
t.Fatal(err)
}
t.Log("test ok")
}
type MockChain struct{}
func (mc MockChain) DoChain(ctx eocontext.EoContext) error {
return nil
}
func (mc MockChain) Destroy() {
}
type HttpContext struct {
}
// AcceptTime implements http_context.IHttpContext.
func (h HttpContext) AcceptTime() time.Time {
panic("unimplemented")
}
// Assert implements http_context.IHttpContext.
func (h HttpContext) Assert(i interface{}) error {
panic("unimplemented")
}
// Clone implements http_context.IHttpContext.
func (h HttpContext) Clone() (eocontext.EoContext, error) {
panic("unimplemented")
}
// Context implements http_context.IHttpContext.
func (h HttpContext) Context() context.Context {
panic("unimplemented")
}
// FastFinish implements http_context.IHttpContext.
func (h HttpContext) FastFinish() {
panic("unimplemented")
}
// GetBalance implements http_context.IHttpContext.
func (h HttpContext) GetBalance() eocontext.BalanceHandler {
panic("unimplemented")
}
// GetComplete implements http_context.IHttpContext.
func (h HttpContext) GetComplete() eocontext.CompleteHandler {
panic("unimplemented")
}
// GetEntry implements http_context.IHttpContext.
func (h HttpContext) GetEntry() eosc.IEntry {
panic("unimplemented")
}
// GetFinish implements http_context.IHttpContext.
func (h HttpContext) GetFinish() eocontext.FinishHandler {
panic("unimplemented")
}
// GetLabel implements http_context.IHttpContext.
func (h HttpContext) GetLabel(name string) string {
panic("unimplemented")
}
// GetUpstreamHostHandler implements http_context.IHttpContext.
func (h HttpContext) GetUpstreamHostHandler() eocontext.UpstreamHostHandler {
panic("unimplemented")
}
// IsCloneable implements http_context.IHttpContext.
func (h HttpContext) IsCloneable() bool {
panic("unimplemented")
}
// Labels implements http_context.IHttpContext.
func (h HttpContext) Labels() map[string]string {
panic("unimplemented")
}
// LocalAddr implements http_context.IHttpContext.
func (h HttpContext) LocalAddr() net.Addr {
panic("unimplemented")
}
// LocalIP implements http_context.IHttpContext.
func (h HttpContext) LocalIP() net.IP {
panic("unimplemented")
}
// LocalPort implements http_context.IHttpContext.
func (h HttpContext) LocalPort() int {
panic("unimplemented")
}
// Proxies implements http_context.IHttpContext.
func (h HttpContext) Proxies() []http_context.IProxy {
panic("unimplemented")
}
// Proxy implements http_context.IHttpContext.
func (h HttpContext) Proxy() http_context.IRequest {
return Request{}
}
// RealIP implements http_context.IHttpContext.
func (h HttpContext) RealIP() string {
panic("unimplemented")
}
// Request implements http_context.IHttpContext.
func (h HttpContext) Request() http_context.IRequestReader {
panic("unimplemented")
}
// RequestId implements http_context.IHttpContext.
func (h HttpContext) RequestId() string {
panic("unimplemented")
}
// Response implements http_context.IHttpContext.
func (h HttpContext) Response() http_context.IResponse {
panic("unimplemented")
}
// Scheme implements http_context.IHttpContext.
func (h HttpContext) Scheme() string {
panic("unimplemented")
}
// SendTo implements http_context.IHttpContext.
func (h HttpContext) SendTo(scheme string, node eocontext.INode, timeout time.Duration) error {
panic("unimplemented")
}
// SetBalance implements http_context.IHttpContext.
func (h HttpContext) SetBalance(handler eocontext.BalanceHandler) {
panic("unimplemented")
}
// SetCompleteHandler implements http_context.IHttpContext.
func (h HttpContext) SetCompleteHandler(handler eocontext.CompleteHandler) {
panic("unimplemented")
}
// SetFinish implements http_context.IHttpContext.
func (h HttpContext) SetFinish(handler eocontext.FinishHandler) {
panic("unimplemented")
}
// SetLabel implements http_context.IHttpContext.
func (h HttpContext) SetLabel(name string, value string) {
panic("unimplemented")
}
// SetUpstreamHostHandler implements http_context.IHttpContext.
func (h HttpContext) SetUpstreamHostHandler(handler eocontext.UpstreamHostHandler) {
panic("unimplemented")
}
// Value implements http_context.IHttpContext.
func (h HttpContext) Value(key interface{}) interface{} {
panic("unimplemented")
}
// WithValue implements http_context.IHttpContext.
func (h HttpContext) WithValue(key interface{}, val interface{}) {
panic("unimplemented")
}
type Request struct {
}
// Body implements http_context.IRequest.
func (r Request) Body() http_context.IBodyDataWriter {
panic("unimplemented")
}
// ContentLength implements http_context.IRequest.
func (r Request) ContentLength() int {
panic("unimplemented")
}
// ContentType implements http_context.IRequest.
func (r Request) ContentType() string {
return "application/json; charset=utf-8"
}
// Header implements http_context.IRequest.
func (r Request) Header() http_context.IHeaderWriter {
panic("unimplemented")
}
// Method implements http_context.IRequest.
func (r Request) Method() string {
panic("unimplemented")
}
// SetMethod implements http_context.IRequest.
func (r Request) SetMethod(method string) {
panic("unimplemented")
}
// URI implements http_context.IRequest.
func (r Request) URI() http_context.IURIWriter {
return URIWriter{}
}
type URIWriter struct {
host string
}
func (writer URIWriter) SetPath(string) {}
func (writer URIWriter) SetScheme(scheme string) {}
func (writer URIWriter) SetHost(host string) {
writer.host = host
}
func (writer URIWriter) RequestURI() string { return "" }
func (writer URIWriter) Scheme() string { return "" }
func (writer URIWriter) RawURL() string { return "" }
func (writer URIWriter) Host() string { return writer.host }
func (writer URIWriter) Path() string { return "" }
func (writer URIWriter) SetQuery(key, value string) {}
func (writer URIWriter) AddQuery(key, value string) {}
func (writer URIWriter) DelQuery(key string) {}
func (writer URIWriter) SetRawQuery(raw string) {}
func (writer URIWriter) GetQuery(key string) string { return "" }
func (writer URIWriter) RawQuery() string { return "" }

View File

@@ -105,13 +105,14 @@ func (a *tActuator) Strategy(ctx eocontext.EoContext, next eocontext.IChain) err
}
break
}
ctx.SetLabel("block_name", name)
if !pass {
ctx.SetLabel("handler", "visit")
httpCtx.Response().SetStatus(403, "")
errInfo := "not allowed"
httpCtx.Response().SetBody([]byte(errInfo))
ctx.WithValue("is_block", true)
ctx.SetLabel("block_name", name)
return errors.New(errInfo)
}
if next != nil {

4
go.mod
View File

@@ -11,7 +11,7 @@ require (
github.com/clbanning/mxj v1.8.4
github.com/coocood/freecache v1.2.2
github.com/dubbogo/gost v1.13.1
github.com/eolinker/eosc v0.18.1
github.com/eolinker/eosc v0.18.2
github.com/fasthttp/websocket v1.5.0
github.com/fullstorydev/grpcurl v1.8.7
github.com/go-redis/redis/v8 v8.11.5
@@ -26,9 +26,11 @@ require (
github.com/ohler55/ojg v1.12.9
github.com/pkg/sftp v1.13.4
github.com/polarismesh/polaris-go v1.1.0
github.com/redis/go-redis/v9 v9.7.0
github.com/robertkrimen/otto v0.0.0-20211024170158-b87d35c0b86f
github.com/soheilhy/cmux v0.1.5
github.com/stretchr/testify v1.9.0
github.com/traefik/yaegi v0.16.1
github.com/urfave/cli/v2 v2.23.4
github.com/valyala/fasthttp v1.47.0
golang.org/x/crypto v0.21.0