diff --git a/app/console/config/cluster.yaml b/app/console/config/cluster.yaml
index 27cb5a8..d6490fb 100644
--- a/app/console/config/cluster.yaml
+++ b/app/console/config/cluster.yaml
@@ -1,5 +1,6 @@
cluster:
- - name: "Default"
+ -
+ name: "Default"
title: "默认机房"
note: "默认机房"
db:
diff --git a/app/console/main.go b/app/console/main.go
index 2ffe1a3..1635546 100644
--- a/app/console/main.go
+++ b/app/console/main.go
@@ -12,8 +12,11 @@ import (
)
var (
+ // UserPassword 用户密码
UserPassword string
+ // UserName 用户名
UserName string
+ // ConfFilePath 配置文件地址
ConfFilePath = "./config/goku.conf"
)
diff --git a/app/goku-node/main.go b/app/goku-node/main.go
index 6e3937d..0554b55 100644
--- a/app/goku-node/main.go
+++ b/app/goku-node/main.go
@@ -13,7 +13,7 @@ import (
"github.com/eolinker/goku-api-gateway/common/database"
"github.com/eolinker/goku-api-gateway/common/general"
- "github.com/eolinker/goku-api-gateway/common/redis-manager"
+ redis_manager "github.com/eolinker/goku-api-gateway/common/redis-manager"
goku_node "github.com/eolinker/goku-api-gateway/goku-node"
"github.com/eolinker/goku-api-gateway/server/entity"
)
@@ -69,11 +69,11 @@ func main() {
return
}
goku_node.InitLog()
- log.Debug("goku_node.InitLog")
+ log.Debug("gokNode.InitLog")
r := redis_manager.Create(&config.Redis)
redis_manager.SetDefault(r)
- log.Debug("redis_manager.SetDefault")
+ log.Debug("redis-manager.SetDefault")
// 其他需要初始化的模块
_ = general.General()
diff --git a/build/console/resources/html/redisAlert.html b/build/console/resources/html/redisAlert.html
deleted file mode 100644
index e608733..0000000
--- a/build/console/resources/html/redisAlert.html
+++ /dev/null
@@ -1,44 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- GoKu Gateway EE
- |
-
-
-
- GoKu告警:Redis节点出现异常
- |
-
-
-
- GoKu接口网关于
- $alertTime 监控到以下Redis节点出现异常,详细告警内容请于
- $alertLogPath 文件夹查看。
- |
-
-
-
- Redis异常节点列表
- |
-
-
-
- $redisList
- |
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/build/console/resources/html/monitorAlert.html b/build/goku-node/resources/html/currentAlert.html
similarity index 63%
rename from build/console/resources/html/monitorAlert.html
rename to build/goku-node/resources/html/currentAlert.html
index a5c902a..c3d60e8 100644
--- a/build/console/resources/html/monitorAlert.html
+++ b/build/goku-node/resources/html/currentAlert.html
@@ -14,23 +14,28 @@
- GoKu告警:节点自动重启失败,请及时重启节点。
+ GoKu告警:$requestURL接口在$alertPeriod分钟内转发失败$alertCount次
|
- GoKu接口网关于 $alertTime
- 检测到以下节点重启失败,详细日志内容请于 ./log/nodeMonitorLog 文件查看。
+ GoKu接口网关于 $alertTime 监控到
+ $requestURL 接口在 $alertPeriod 分钟内转发失败达到 $alertCount 次,详细告警内容请于
+ $alertLogPath 文件夹查看。
|
- 自动重启失败的节点列表
+ 接口基本信息
|
- $nodeList
+ 接口名称:$apiName
+ apiID:$apiID
+ 请求路径:$requestURL
+ 转发路径:$targetServer
+ 映射路径:$proxyURL
|
diff --git a/common/auto-form/auto.go b/common/auto-form/auto.go
index b995796..9da3fd3 100644
--- a/common/auto-form/auto.go
+++ b/common/auto-form/auto.go
@@ -11,10 +11,12 @@ import (
"unsafe"
)
+//Values values
type Values interface {
Get(key string) (string, bool)
}
+//ValuesForm valuesForm
type ValuesForm map[string][]string
// Get gets the first value associated with the given key.
@@ -41,6 +43,7 @@ type (
ContextHandle interface {
SetContext(ctx Values) error
}
+ //CheckOptHandler 判断是否有opt字段
CheckOptHandler interface {
IsOpt(key string) bool
}
@@ -50,6 +53,7 @@ type (
}
)
+//IsOpt 是否是opt字段
func IsOpt(key string, c interface{}) bool {
val := reflect.ValueOf(c).Elem()
typ := val.Type()
@@ -67,8 +71,10 @@ func IsOpt(key string, c interface{}) bool {
return false
}
+//ErrorNil error nil
var ErrorNil = errors.New("target is nil")
-// SetContext 从url.Values中完成配置字段,context中不存在时,使用 default
+
+// SetValues 从url.Values中完成配置字段,context中不存在时,使用 default
// 字段格式 opt:"name,require" default:"default value" min:"min value" max:"max value"
// require 为可选,表示该字段是否为必填
func SetValues(values url.Values, c interface{}) error {
diff --git a/common/conf/conf.go b/common/conf/conf.go
index 975ea2b..abb1b1b 100644
--- a/common/conf/conf.go
+++ b/common/conf/conf.go
@@ -1,4 +1,3 @@
-// 读取配置信息
package conf
import (
@@ -13,20 +12,28 @@ var (
lastFile = ""
)
+//Get get
func Get(name string) (string, bool) {
v, has := _Configure[name]
return v, has
}
+
+//Set set
func Set(name, value string) {
_Configure[name] = value
}
+//Value value
func Value(name string) string {
return _Configure[name]
}
+
+//Reload reload
func Reload() {
ReadConfigure(lastFile)
}
+
+//MastValue mastValue
func MastValue(name string, def string) string {
v, h := _Configure[name]
if h {
@@ -34,6 +41,8 @@ func MastValue(name string, def string) string {
}
return def
}
+
+//ReadConfigure 读取配置
func ReadConfigure(filepath string) error {
file, err := os.Open(filepath)
if err != nil {
@@ -53,14 +62,8 @@ func ReadConfigure(filepath string) error {
return nil
}
-// 更新配置文件
+//Save 更新配置文件
func Save() (bool, error) {
- //file, err := os.OpenFile(lastFile, os.O_CREATE|os.O_WRONLY, 0666)
- //if err != nil {
- // panic(err)
- //}
- //defer file.Close()
-
confStr, err := yaml.Marshal(_Configure)
if err != nil {
return false, err
diff --git a/common/database/conn.go b/common/database/conn.go
index ed08a01..b83adab 100644
--- a/common/database/conn.go
+++ b/common/database/conn.go
@@ -3,6 +3,7 @@ package database
import (
"database/sql"
log "github.com/eolinker/goku-api-gateway/goku-log"
+ // mysql包
_ "github.com/go-sql-driver/mysql"
)
@@ -14,6 +15,7 @@ var (
defaultDB *sql.DB
)
+//InitConnection 初始化连接
func InitConnection(config Config) error {
db, e := getConnection(config)
defaultDB = db
@@ -45,6 +47,7 @@ func getConnection(config Config) (*sql.DB, error) {
}
+//GetConnection 获取连接
func GetConnection() *sql.DB {
return defaultDB
diff --git a/common/endless/endless.go b/common/endless/endless.go
index de44ffc..41e5183 100644
--- a/common/endless/endless.go
+++ b/common/endless/endless.go
@@ -20,12 +20,19 @@ import (
)
const (
+ //PRE_SIGNAL pre signal
PRE_SIGNAL = iota
+
+ //POST_SIGNAL post signal
POST_SIGNAL
+ //STATE_INIT state init
STATE_INIT
+ //STATE_RUNNING state running
STATE_RUNNING
+ //STATE_SHUTTING_DOWN state shutting down
STATE_SHUTTING_DOWN
+ //STATE_TERMINATE state terminate
STATE_TERMINATE
)
@@ -36,10 +43,14 @@ var (
socketPtrOffsetMap map[string]uint
runningServersForked bool
- DefaultReadTimeOut time.Duration
- DefaultWriteTimeOut time.Duration
+ //DefaultReadTimeOut 默认读超时时间
+ DefaultReadTimeOut time.Duration
+ //DefaultWriteTimeOut 默认写超时时间
+ DefaultWriteTimeOut time.Duration
+ //DefaultMaxHeaderBytes 默认请求头最大字节数
DefaultMaxHeaderBytes int
- DefaultHammerTime time.Duration
+ //DefaultHammerTime default hammer time
+ DefaultHammerTime time.Duration
isChild bool
socketOrder string
@@ -47,7 +58,7 @@ var (
hookableSignals []os.Signal
)
-var isStop bool = true
+var isStop = true
func init() {
runningServerReg = sync.RWMutex{}
diff --git a/common/general/general.go b/common/general/general.go
index fb6e6f5..58142a9 100644
--- a/common/general/general.go
+++ b/common/general/general.go
@@ -1,5 +1,6 @@
package general
+//InitFunc init func
type InitFunc func() error
var (
@@ -7,10 +8,13 @@ var (
_laterFunc []InitFunc
)
+//RegeditInit 初始化注册
func RegeditInit(fn InitFunc) {
_initFunc = append(_initFunc, fn)
}
+
+//General general
func General() error {
for _, fn := range _initFunc {
if err := fn(); err != nil {
@@ -25,6 +29,7 @@ func General() error {
return nil
}
+//RegeditLater regedit later
func RegeditLater(fn InitFunc) {
_laterFunc = append(_laterFunc, fn)
}
diff --git a/common/redis-manager/factory.go b/common/redis-manager/factory.go
index 5e87403..06c04f9 100644
--- a/common/redis-manager/factory.go
+++ b/common/redis-manager/factory.go
@@ -1,4 +1,4 @@
-package redis_manager
+package redismanager
import (
"fmt"
@@ -11,6 +11,7 @@ const (
_PoolSize = 2000
)
+//Create 创建
func Create(config RedisConfig) Redis {
switch config.GetMode() {
diff --git a/common/redis-manager/function.go b/common/redis-manager/function.go
index f517cee..3842e7c 100644
--- a/common/redis-manager/function.go
+++ b/common/redis-manager/function.go
@@ -1,4 +1,4 @@
-package redis_manager
+package redismanager
//
//func GetKeys(r Redis, pattern string) ([]string, error) {
diff --git a/common/redis-manager/manager.go b/common/redis-manager/manager.go
index 3995fa1..86c89fa 100644
--- a/common/redis-manager/manager.go
+++ b/common/redis-manager/manager.go
@@ -1,4 +1,4 @@
-package redis_manager
+package redismanager
import (
"sync"
@@ -11,6 +11,7 @@ var (
locker sync.RWMutex
)
+//InitRedisOfCluster 初始化集群redis
func InitRedisOfCluster(rs map[string]RedisConfig) {
locker.Lock()
defer locker.Unlock()
@@ -27,6 +28,8 @@ func get(name string) (Redis, bool) {
return r, h
}
+
+//Get 获取redis
func Get(name string) (Redis, bool) {
r, has := get(name)
diff --git a/common/redis-manager/proxy.go b/common/redis-manager/proxy.go
index eb2cbc1..4af603f 100644
--- a/common/redis-manager/proxy.go
+++ b/common/redis-manager/proxy.go
@@ -1,4 +1,4 @@
-package redis_manager
+package redismanager
import (
"github.com/go-redis/redis"
diff --git a/common/redis-manager/redis.go b/common/redis-manager/redis.go
index b66c5a5..437b4fe 100644
--- a/common/redis-manager/redis.go
+++ b/common/redis-manager/redis.go
@@ -1,12 +1,15 @@
-package redis_manager
+package redismanager
import "github.com/go-redis/redis"
const (
- RedisModeCluster = "cluster"
- RedisModeStand = "stand"
+ //RedisModeCluster cluster模式
+ RedisModeCluster = "cluster"
+ //RedisModeStand stand模式
+ RedisModeStand = "stand"
)
+//Redis redis
type Redis interface {
redis.Cmdable
GetConfig() RedisConfig
@@ -14,6 +17,7 @@ type Redis interface {
Nodes() []string
}
+//RedisConfig redis config
type RedisConfig interface {
GetMode() string
GetAddrs() []string
diff --git a/common/redis-manager/redis_conn.go b/common/redis-manager/redis_conn.go
index b3921ca..3b24dff 100644
--- a/common/redis-manager/redis_conn.go
+++ b/common/redis-manager/redis_conn.go
@@ -1,4 +1,4 @@
-package redis_manager
+package redismanager
import (
"sync"
@@ -10,11 +10,12 @@ var (
defLocker sync.Locker
)
+//SetDefault 设置默认redis
func SetDefault(r Redis) {
def = r
}
-// 获取redis连接
+//GetConnection 获取redis连接
func GetConnection() Redis {
if def != nil {
return def
diff --git a/common/version/version.go b/common/version/version.go
index 6f6bcc4..48e95ff 100644
--- a/common/version/version.go
+++ b/common/version/version.go
@@ -1,3 +1,4 @@
package version
+//Version 版本号
const Version = "3.0.0"
diff --git a/console/admin/alert.go b/console/admin/alert.go
index 694ef89..5e6ac0a 100644
--- a/console/admin/alert.go
+++ b/console/admin/alert.go
@@ -10,7 +10,7 @@ import (
"github.com/eolinker/goku-api-gateway/utils"
)
-// 新增告警信息
+// AddAlertMsg 新增告警信息
func AddAlertMsg(httpResponse http.ResponseWriter, httpRequest *http.Request) {
nodeIP := httpRequest.RemoteAddr
diff --git a/console/admin/controller.go b/console/admin/controller.go
index ce84b69..654c6a3 100644
--- a/console/admin/controller.go
+++ b/console/admin/controller.go
@@ -6,6 +6,7 @@ import (
"strings"
)
+//GetIpPort 获取IP端口
func GetIpPort(r *http.Request) (string, int, error) {
ip := r.RemoteAddr
ip = ip[:strings.Index(ip, ":")]
diff --git a/console/admin/register.go b/console/admin/register.go
index 1845b09..8a15624 100644
--- a/console/admin/register.go
+++ b/console/admin/register.go
@@ -10,6 +10,7 @@ import (
"strconv"
)
+//Register 注册
func Register(w http.ResponseWriter, r *http.Request) {
ip, port, err := GetIpPort(r)
@@ -28,7 +29,7 @@ func Register(w http.ResponseWriter, r *http.Request) {
func regedister(ip string, port int) (*entity.ClusterInfo, error) {
- has, node, err := node.GetNodeInfoByIpPort(ip, port)
+ has, node, err := node.GetNodeInfoByIPPort(ip, port)
if err != nil {
return nil, err
}
diff --git a/console/admin/server.go b/console/admin/server.go
index 0ebe4de..a77ae8d 100644
--- a/console/admin/server.go
+++ b/console/admin/server.go
@@ -4,6 +4,7 @@ import (
"net/http"
)
+//StartServer 开启admin服务
func StartServer(bind string) error {
handler := router()
return http.ListenAndServe(bind, handler)
diff --git a/console/cluster.go b/console/cluster.go
index 9ff4d14..a91a63c 100644
--- a/console/cluster.go
+++ b/console/cluster.go
@@ -5,7 +5,7 @@ import (
"strconv"
"github.com/eolinker/goku-api-gateway/common/conf"
- "github.com/eolinker/goku-api-gateway/common/redis-manager"
+ redis_manager "github.com/eolinker/goku-api-gateway/common/redis-manager"
cluster2 "github.com/eolinker/goku-api-gateway/server/cluster"
console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
"github.com/eolinker/goku-api-gateway/server/entity"
@@ -49,6 +49,8 @@ func getDefaultDatabase() (*entity.ClusterDB, error) {
Database: conf.Value("db_name"),
}, nil
}
+
+//InitClusters 初始化集群
func InitClusters() {
infos, err := loadCluster(conf.MastValue("cluster_config", "config/cluster.yaml"))
diff --git a/console/controller/account/guest.go b/console/controller/account/guest.go
index 99e20a4..6431cdb 100644
--- a/console/controller/account/guest.go
+++ b/console/controller/account/guest.go
@@ -9,7 +9,7 @@ import (
"strconv"
)
-// 用户登录
+//Login 用户登录
func Login(httpResponse http.ResponseWriter, httpRequest *http.Request) {
//resultInfo := entity2.ResultInfo{}
diff --git a/console/controller/account/user.go b/console/controller/account/user.go
index f1f23f8..05167cc 100644
--- a/console/controller/account/user.go
+++ b/console/controller/account/user.go
@@ -11,7 +11,7 @@ import (
"github.com/eolinker/goku-api-gateway/utils"
)
-// 用户注销
+//Logout 用户注销
func Logout(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userIDCookie := http.Cookie{Name: "userID", Path: "/", MaxAge: -1}
@@ -23,7 +23,7 @@ func Logout(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 修改账户信息
+//EditPassword 修改账户信息
func EditPassword(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationEDIT)
if e != nil {
@@ -37,8 +37,8 @@ func EditPassword(httpResponse http.ResponseWriter, httpRequest *http.Request) {
controller.WriteError(httpResponse,
"110005",
"user",
- "[ERROR]Illegal oldPassword!",
- errors.New("[ERROR]Illegal oldPassword!"))
+ "[error]illegal oldPassword!",
+ errors.New("[error]illegal oldPassword"))
return
}
if flag, _ := regexp.MatchString("^[0-9a-zA-Z]{32}$", newPassword); !flag {
@@ -46,8 +46,8 @@ func EditPassword(httpResponse http.ResponseWriter, httpRequest *http.Request) {
controller.WriteError(httpResponse,
"110006",
"user",
- "[ERROR]Illegal newPassword!",
- errors.New("[ERROR]Illegal newPassword!"))
+ "[error]illegal newPassword!",
+ errors.New("[error]illegal newPassword"))
return
}
flag, result, err := account.EditPassword(oldPassword, newPassword, userID)
@@ -70,7 +70,7 @@ func EditPassword(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 获取用户信息
+//GetUserInfo 获取用户信息
func GetUserInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationEDIT)
if e != nil {
@@ -89,7 +89,7 @@ func GetUserInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 获取用户类型
+//GetUserType 获取用户类型
func GetUserType(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationEDIT)
if e != nil {
@@ -107,7 +107,7 @@ func GetUserType(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 判断是否是管理员
+//CheckUserIsAdmin 判断是否是管理员
func CheckUserIsAdmin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationEDIT)
if e != nil {
@@ -130,7 +130,7 @@ func CheckUserIsAdmin(httpResponse http.ResponseWriter, httpRequest *http.Reques
return
}
-// 判断是否是超级管理员
+//CheckUserIsSuperAdmin 判断是否是超级管理员
func CheckUserIsSuperAdmin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationEDIT)
if e != nil {
@@ -154,7 +154,7 @@ func CheckUserIsSuperAdmin(httpResponse http.ResponseWriter, httpRequest *http.R
return
}
-// 检查用户权限
+//CheckUserPermission 检查用户权限
func CheckUserPermission(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationEDIT)
if e != nil {
diff --git a/console/controller/alert/alert.go b/console/controller/alert/alert.go
index 9229d41..d9ed979 100644
--- a/console/controller/alert/alert.go
+++ b/console/controller/alert/alert.go
@@ -39,7 +39,7 @@ func GetAlertMsgList(httpResponse http.ResponseWriter, httpRequest *http.Request
return
}
-// 清空告警信息列表
+//ClearAlertMsg 清空告警信息列表
func ClearAlertMsg(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAlert, controller.OperationEDIT)
if e != nil {
@@ -61,7 +61,7 @@ func ClearAlertMsg(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 删除告警信息
+//DeleteAlertMsg 删除告警信息
func DeleteAlertMsg(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAlert, controller.OperationEDIT)
if e != nil {
@@ -98,6 +98,7 @@ func DeleteAlertMsg(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
+//GetAlertConfig 获取告警配置
func GetAlertConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAlert, controller.OperationREAD)
if e != nil {
diff --git a/console/controller/api/api-balance-batch.go b/console/controller/api/api-balance-batch.go
index c446032..2d46593 100644
--- a/console/controller/api/api-balance-batch.go
+++ b/console/controller/api/api-balance-batch.go
@@ -8,7 +8,8 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/api"
)
-func BatchSetBalanceApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//BatchSetBalanceAPI 批量设置接口负载
+func BatchSetBalanceAPI(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -17,7 +18,7 @@ func BatchSetBalanceApi(httpResponse http.ResponseWriter, httpRequest *http.Requ
apiIDList := httpRequest.PostFormValue("apiIDList")
balanceName := httpRequest.PostFormValue("balance")
- result, err := api.BatchEditApiBalance(strings.Split(apiIDList, ","), balanceName)
+ result, err := api.BatchEditAPIBalance(strings.Split(apiIDList, ","), balanceName)
if err != nil {
controller.WriteError(httpResponse, "190015", "api", result, err)
return
diff --git a/console/controller/api/api.go b/console/controller/api/api.go
index f525f4d..3300151 100644
--- a/console/controller/api/api.go
+++ b/console/controller/api/api.go
@@ -11,7 +11,8 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/api"
)
-func AddApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//AddAPI 新增接口
+func AddAPI(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -106,7 +107,7 @@ func AddApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
// return
// }
- flag, id, err := api.AddApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol, pjID, gID, t, count, apiValve, mgID, userID)
+ flag, id, err := api.AddAPI(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol, pjID, gID, t, count, apiValve, mgID, userID)
if !flag {
controller.WriteError(httpResponse,
@@ -118,7 +119,8 @@ func AddApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-func EditApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//EditAPI 编辑接口
+func EditAPI(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -216,7 +218,7 @@ func EditApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
// return
// }
- flag, err := api.EditApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol, pjID, gID, t, count, apiValve, aID, mgID, userID)
+ flag, err := api.EditAPI(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol, pjID, gID, t, count, apiValve, aID, mgID, userID)
if !flag {
controller.WriteError(httpResponse, "190000", "api", "[ERROR]apiID does not exist!", err)
@@ -229,8 +231,8 @@ func EditApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 获取接口信息
-func GetApiInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAPIInfo 获取接口信息
+func GetAPIInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
return
@@ -244,7 +246,7 @@ func GetApiInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
- flag, result, err := api.GetApiInfo(aID)
+ flag, result, err := api.GetAPIInfo(aID)
if !flag {
controller.WriteError(httpResponse, "190000", "api", "[ERROR]The api does not exist!", err)
return
@@ -302,7 +304,8 @@ func GetAPIIDList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-func GetApiList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAPIList 获取接口列表
+func GetAPIList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
return
@@ -362,8 +365,8 @@ func GetApiList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// BatchEditApiGroup 批量修改接口分组
-func BatchEditApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+// BatchEditAPIGroup 批量修改接口分组
+func BatchEditAPIGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -376,7 +379,7 @@ func BatchEditApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Reque
controller.WriteError(httpResponse, "190015", "api", "[ERROR]Illegal groupID!", nil)
return
}
- flag, result, err := api.BatchEditApiGroup(strings.Split(apiIDList, ","), gID)
+ flag, result, err := api.BatchEditAPIGroup(strings.Split(apiIDList, ","), gID)
if !flag {
controller.WriteError(httpResponse, "190015", "api", result, err)
return
@@ -386,8 +389,8 @@ func BatchEditApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Reque
return
}
-// 批量删除接口
-func BatchDeleteApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//BatchDeleteAPI 批量删除接口
+func BatchDeleteAPI(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -395,7 +398,7 @@ func BatchDeleteApi(httpResponse http.ResponseWriter, httpRequest *http.Request)
apiIDList := httpRequest.PostFormValue("apiIDList")
- flag, result, err := api.BatchDeleteApi(apiIDList)
+ flag, result, err := api.BatchDeleteAPI(apiIDList)
if !flag {
controller.WriteError(httpResponse, "190000", "api", result, err)
@@ -407,8 +410,8 @@ func BatchDeleteApi(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 获取接口负责人列表
-func GetApiManagerList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAPIManagerList 获取接口负责人列表
+func GetAPIManagerList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
return
@@ -423,7 +426,8 @@ func GetApiManagerList(httpResponse http.ResponseWriter, httpRequest *http.Reque
return
}
-func CopyApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//CopyAPI 接口复制
+func CopyAPI(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -471,12 +475,12 @@ func CopyApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
- flag, apiInfo, err := api.GetApiInfo(aID)
+ flag, apiInfo, err := api.GetAPIInfo(aID)
if !flag {
controller.WriteError(httpResponse, "190000", "api", "[ERROR]apiID does not exist!", nil)
return
}
- flag, id, err := api.AddApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, strconv.FormatBool(apiInfo.StripPrefix), strconv.FormatBool(apiInfo.StripSlash), balanceName, protocol, pjID, gID, apiInfo.Timeout, apiInfo.RetryConut, apiInfo.Valve, apiInfo.ManagerID, userID)
+ flag, id, err := api.AddAPI(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, strconv.FormatBool(apiInfo.StripPrefix), strconv.FormatBool(apiInfo.StripSlash), balanceName, protocol, pjID, gID, apiInfo.Timeout, apiInfo.RetryConut, apiInfo.Valve, apiInfo.ManagerID, userID)
if !flag {
controller.WriteError(httpResponse, "190000", "api", "[ERROR]Fail to add api!", err)
return
diff --git a/console/controller/api/apiGroup.go b/console/controller/api/apiGroup.go
index 69cc5ae..993c108 100644
--- a/console/controller/api/apiGroup.go
+++ b/console/controller/api/apiGroup.go
@@ -9,8 +9,8 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/project"
)
-// 新建接口分组
-func AddApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//AddAPIGroup 新建接口分组
+func AddAPIGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -51,7 +51,7 @@ func AddApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
- flag, result, err := api.AddApiGroup(groupName, pjID, pgID)
+ flag, result, err := api.AddAPIGroup(groupName, pjID, pgID)
if !flag {
controller.WriteError(httpResponse,
@@ -66,8 +66,8 @@ func AddApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 修改接口分组
-func EditApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//EditAPIGroup 修改接口分组
+func EditAPIGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -107,7 +107,7 @@ func EditApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
- flag, result, err := api.EditApiGroup(groupName, gID, pjID)
+ flag, result, err := api.EditAPIGroup(groupName, gID, pjID)
if !flag {
controller.WriteError(httpResponse,
@@ -118,8 +118,8 @@ func EditApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 删除接口分组
-func DeleteApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//DeleteAPIGroup 删除接口分组
+func DeleteAPIGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -144,7 +144,7 @@ func DeleteApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
- flag, result, err := api.DeleteApiGroup(pjID, gID)
+ flag, result, err := api.DeleteAPIGroup(pjID, gID)
if !flag {
controller.WriteError(httpResponse,
@@ -156,8 +156,8 @@ func DeleteApiGroup(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 获取接口分组列表
-func GetApiGroupList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAPIGroupList 获取接口分组列表
+func GetAPIGroupList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
return
@@ -172,7 +172,7 @@ func GetApiGroupList(httpResponse http.ResponseWriter, httpRequest *http.Request
return
}
- flag, result, err := api.GetApiGroupList(pjID)
+ flag, result, err := api.GetAPIGroupList(pjID)
if !flag {
controller.WriteError(httpResponse,
@@ -186,6 +186,7 @@ func GetApiGroupList(httpResponse http.ResponseWriter, httpRequest *http.Request
return
}
-func UpdateApiGroupScript(httpResponse http.ResponseWriter, httpRequest *http.Request) {
- api.UpdateApiGroupScript()
+//UpdateAPIGroupScript 更新接口分组脚本
+func UpdateAPIGroupScript(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+ api.UpdateAPIGroupScript()
}
diff --git a/console/controller/api/apiPlugin.go b/console/controller/api/apiPlugin.go
index 112ab72..d68b0f2 100644
--- a/console/controller/api/apiPlugin.go
+++ b/console/controller/api/apiPlugin.go
@@ -12,8 +12,8 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/strategy"
)
-// 新增插件到接口
-func AddPluginToApi(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//AddPluginToAPI 新增插件到接口
+func AddPluginToAPI(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -41,7 +41,7 @@ func AddPluginToApi(httpResponse http.ResponseWriter, httpRequest *http.Request)
controller.WriteError(httpResponse, "240005", "apiPlugin", "[ERROR]The plugin does not exist!", err)
return
}
- flag, err = api.CheckApiIsExist(aID)
+ flag, err = api.CheckAPIIsExist(aID)
if !flag {
controller.WriteError(httpResponse, "240012", "apiPlugin", "[ERROR]The api does not exist!", err)
@@ -56,17 +56,17 @@ func AddPluginToApi(httpResponse http.ResponseWriter, httpRequest *http.Request)
}
id := 0
- exist, err := api.CheckPluginIsExistInApi(strategyID, pluginName, aID)
+ exist, err := api.CheckPluginIsExistInAPI(strategyID, pluginName, aID)
if exist {
- flag, resultDesc, err := api.EditApiPluginConfig(pluginName, pluginConfig, strategyID, aID, userID)
+ flag, resultDesc, err := api.EditAPIPluginConfig(pluginName, pluginConfig, strategyID, aID, userID)
if !flag {
controller.WriteError(httpResponse, "240000", "apiPlugin", resultDesc.(string), err)
return
}
id = resultDesc.(int)
} else {
- flag, resultDesc, err := api.AddPluginToApi(pluginName, pluginConfig, strategyID, aID, userID)
+ flag, resultDesc, err := api.AddPluginToAPI(pluginName, pluginConfig, strategyID, aID, userID)
if !flag {
controller.WriteError(httpResponse, "240000", "apiPlugin", resultDesc.(string), err)
return
@@ -79,8 +79,8 @@ func AddPluginToApi(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 修改接口插件
-func EditApiPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//EditAPIPluginConfig 修改接口插件
+func EditAPIPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -117,7 +117,7 @@ func EditApiPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Req
return
}
- flag, err = api.CheckApiIsExist(aID)
+ flag, err = api.CheckAPIIsExist(aID)
if !flag {
controller.WriteError(httpResponse,
"240012",
@@ -137,7 +137,7 @@ func EditApiPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Req
return
}
- flag, resultDesc, err := api.EditApiPluginConfig(pluginName, pluginConfig, strategyID, aID, userID)
+ flag, resultDesc, err := api.EditAPIPluginConfig(pluginName, pluginConfig, strategyID, aID, userID)
if !flag {
controller.WriteError(httpResponse,
@@ -151,8 +151,8 @@ func EditApiPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Req
return
}
-// 获取接口插件配置
-func GetApiPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAPIPluginConfig 获取接口插件配置
+func GetAPIPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
return
@@ -172,7 +172,7 @@ func GetApiPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Requ
return
}
- flag, result, err := api.GetApiPluginConfig(aID, strategyID, pluginName)
+ flag, result, err := api.GetAPIPluginConfig(aID, strategyID, pluginName)
if !flag {
resultByte, _ := json.Marshal(map[string]interface{}{
"type": "apiPlugin",
@@ -196,8 +196,8 @@ func GetApiPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Requ
}
-// 获取接口插件配置
-func GetApiPluginList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAPIPluginList 获取接口插件配置
+func GetAPIPluginList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
return
@@ -215,7 +215,7 @@ func GetApiPluginList(httpResponse http.ResponseWriter, httpRequest *http.Reques
return
}
- flag, result, err := api.GetApiPluginList(aID, strategyID)
+ flag, result, err := api.GetAPIPluginList(aID, strategyID)
if !flag {
controller.WriteError(httpResponse,
"240000",
@@ -278,8 +278,8 @@ func GetAPIPluginInStrategyByAPIID(httpResponse http.ResponseWriter, httpRequest
// controller.WriteResultInfo(httpResponse, "apiPlugin", "apiPluginList", result)
}
-// 获取策略组中所有接口插件列表
-func GetAllApiPluginInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAllAPIPluginInStrategy 获取策略组中所有接口插件列表
+func GetAllAPIPluginInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
return
@@ -287,7 +287,7 @@ func GetAllApiPluginInStrategy(httpResponse http.ResponseWriter, httpRequest *ht
strategyID := httpRequest.PostFormValue("strategyID")
- flag, result, err := api.GetAllApiPluginInStrategy(strategyID)
+ flag, result, err := api.GetAllAPIPluginInStrategy(strategyID)
if !flag {
controller.WriteError(httpResponse,
@@ -303,8 +303,8 @@ func GetAllApiPluginInStrategy(httpResponse http.ResponseWriter, httpRequest *ht
return
}
-// 批量修改策略组插件状态
-func BatchStartApiPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//BatchStartAPIPlugin 批量修改策略组插件状态
+func BatchStartAPIPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -321,7 +321,7 @@ func BatchStartApiPlugin(httpResponse http.ResponseWriter, httpRequest *http.Req
return
}
- flag, result, err := api.BatchEditApiPluginStatus(connIDList, strategyID, 1, userID)
+ flag, result, err := api.BatchEditAPIPluginStatus(connIDList, strategyID, 1, userID)
if !flag {
controller.WriteError(httpResponse,
@@ -336,8 +336,8 @@ func BatchStartApiPlugin(httpResponse http.ResponseWriter, httpRequest *http.Req
return
}
-// 批量修改策略组插件状态
-func BatchStopApiPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//BatchStopAPIPlugin 批量修改策略组插件状态
+func BatchStopAPIPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -354,7 +354,7 @@ func BatchStopApiPlugin(httpResponse http.ResponseWriter, httpRequest *http.Requ
return
}
- flag, _, err := api.BatchEditApiPluginStatus(connIDList, strategyID, 0, userID)
+ flag, _, err := api.BatchEditAPIPluginStatus(connIDList, strategyID, 0, userID)
if !flag {
controller.WriteError(httpResponse,
@@ -369,8 +369,8 @@ func BatchStopApiPlugin(httpResponse http.ResponseWriter, httpRequest *http.Requ
return
}
-// 批量删除策略组插件
-func BatchDeleteApiPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//BatchDeleteAPIPlugin 批量删除策略组插件
+func BatchDeleteAPIPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -387,7 +387,7 @@ func BatchDeleteApiPlugin(httpResponse http.ResponseWriter, httpRequest *http.Re
return
}
- flag, result, err := api.BatchDeleteApiPlugin(connIDList, strategyID)
+ flag, result, err := api.BatchDeleteAPIPlugin(connIDList, strategyID)
if !flag {
controller.WriteError(httpResponse,
@@ -399,7 +399,8 @@ func BatchDeleteApiPlugin(httpResponse http.ResponseWriter, httpRequest *http.Re
controller.WriteResultInfo(httpResponse, "apiPlugin", "", nil)
}
-func GetApiPluginListWithNotAssignApiList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAPIPluginListWithNotAssignAPIList 获取没有绑定接口插件的接口列表
+func GetAPIPluginListWithNotAssignAPIList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
return
@@ -414,7 +415,7 @@ func GetApiPluginListWithNotAssignApiList(httpResponse http.ResponseWriter, http
nil)
return
}
- flag, result, err := api.GetApiPluginListWithNotAssignApiList(strategyID)
+ flag, result, err := api.GetAPIPluginListWithNotAssignAPIList(strategyID)
if !flag {
controller.WriteError(httpResponse,
@@ -428,6 +429,7 @@ func GetApiPluginListWithNotAssignApiList(httpResponse http.ResponseWriter, http
}
-func UpdateAllApiPluginUpdateTag() error {
- return api.UpdateAllApiPluginUpdateTag()
+//UpdateAllAPIPluginUpdateTag 更新所有标识
+func UpdateAllAPIPluginUpdateTag() error {
+ return api.UpdateAllAPIPluginUpdateTag()
}
diff --git a/console/controller/api/import.go b/console/controller/api/import.go
index 9297c94..c2d9e8e 100644
--- a/console/controller/api/import.go
+++ b/console/controller/api/import.go
@@ -12,8 +12,8 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// 导入分组
-func ImportApiGroupFromAms(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//ImportAPIGroupFromAms 导入分组
+func ImportAPIGroupFromAms(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -81,7 +81,7 @@ func ImportApiGroupFromAms(httpResponse http.ResponseWriter, httpRequest *http.R
return
}
- flag, _, err := api.ImportApiGroupFromAms(pjID, userID, groupInfo)
+ flag, _, err := api.ImportAPIGroupFromAms(pjID, userID, groupInfo)
if !flag {
controller.WriteError(httpResponse,
@@ -96,7 +96,7 @@ func ImportApiGroupFromAms(httpResponse http.ResponseWriter, httpRequest *http.R
}
-// 导入项目
+//ImportProjectFromAms 导入项目
func ImportProjectFromAms(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
@@ -168,8 +168,8 @@ func ImportProjectFromAms(httpResponse http.ResponseWriter, httpRequest *http.Re
return
}
-// 导入接口
-func ImportApiFromAms(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//ImportAPIFromAms 导入接口
+func ImportAPIFromAms(httpResponse http.ResponseWriter, httpRequest *http.Request) {
userID, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
return
@@ -228,7 +228,7 @@ func ImportApiFromAms(httpResponse http.ResponseWriter, httpRequest *http.Reques
return
}
- apiList := make([]entity.AmsApiInfo, 0)
+ apiList := make([]entity.AmsAPIInfo, 0)
err = json.Unmarshal(body, &apiList)
if err != nil {
controller.WriteError(httpResponse,
@@ -248,7 +248,7 @@ func ImportApiFromAms(httpResponse http.ResponseWriter, httpRequest *http.Reques
return
}
- flag, _, err := api.ImportApiFromAms(pjID, gID, userID, apiList)
+ flag, _, err := api.ImportAPIFromAms(pjID, gID, userID, apiList)
if !flag {
controller.WriteError(httpResponse,
diff --git a/console/controller/auth/auth.go b/console/controller/auth/auth.go
index 8dcd85e..37af6dd 100644
--- a/console/controller/auth/auth.go
+++ b/console/controller/auth/auth.go
@@ -10,7 +10,7 @@ import (
log "github.com/eolinker/goku-api-gateway/goku-log"
)
-// 获取认证状态
+//GetAuthStatus 获取认证状态
func GetAuthStatus(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationREAD)
if e != nil {
@@ -35,7 +35,7 @@ func GetAuthStatus(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 获取认证信息
+//GetAuthInfo 获取认证信息
func GetAuthInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationREAD)
if e != nil {
@@ -62,7 +62,7 @@ func GetAuthInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
}
-// 编辑认证信息
+//EditAuthInfo 编辑认证信息
func EditAuthInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationEDIT)
if e != nil {
diff --git a/console/controller/balance/add.go b/console/controller/balance/add.go
index d72a236..ef94874 100644
--- a/console/controller/balance/add.go
+++ b/console/controller/balance/add.go
@@ -10,7 +10,7 @@ import (
"github.com/go-sql-driver/mysql"
)
-// 新增负载配置
+//AddBalance 新增负载配置
func AddBalance(w http.ResponseWriter, r *http.Request) {
_, e := controller.CheckLogin(w, r, controller.OperationLoadBalance, controller.OperationEDIT)
diff --git a/console/controller/balance/delete.go b/console/controller/balance/delete.go
index 75662fe..0fac567 100644
--- a/console/controller/balance/delete.go
+++ b/console/controller/balance/delete.go
@@ -8,7 +8,7 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/balance"
)
-// 删除负载配置
+//DeleteBalance 删除负载配置
func DeleteBalance(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationLoadBalance, controller.OperationEDIT)
if e != nil {
@@ -34,7 +34,7 @@ func DeleteBalance(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 批量删除负载
+//BatchDeleteBalance 批量删除负载
func BatchDeleteBalance(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationLoadBalance, controller.OperationEDIT)
diff --git a/console/controller/balance/get.go b/console/controller/balance/get.go
index 02024c5..a726bf0 100644
--- a/console/controller/balance/get.go
+++ b/console/controller/balance/get.go
@@ -7,7 +7,7 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/balance"
)
-// 获取负载信息
+//GetBalanceInfo 获取负载信息
func GetBalanceInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationLoadBalance, controller.OperationREAD)
if e != nil {
diff --git a/console/controller/balance/list.go b/console/controller/balance/list.go
index 6def59d..a581df9 100644
--- a/console/controller/balance/list.go
+++ b/console/controller/balance/list.go
@@ -8,7 +8,7 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/balance"
)
-// 获取负载列表
+//GetBalanceList 获取负载列表
func GetBalanceList(w http.ResponseWriter, r *http.Request) {
_, e := controller.CheckLogin(w, r, controller.OperationLoadBalance, controller.OperationREAD)
if e != nil {
diff --git a/console/controller/balance/save.go b/console/controller/balance/save.go
index 67f9473..8ec187f 100644
--- a/console/controller/balance/save.go
+++ b/console/controller/balance/save.go
@@ -10,7 +10,7 @@ import (
"github.com/go-sql-driver/mysql"
)
-// 新增负载配置
+//SaveBalance 新增负载配置
func SaveBalance(w http.ResponseWriter, r *http.Request) {
_, e := controller.CheckLogin(w, r, controller.OperationLoadBalance, controller.OperationEDIT)
diff --git a/console/controller/balance/simple.go b/console/controller/balance/simple.go
index 2bedcec..43de34a 100644
--- a/console/controller/balance/simple.go
+++ b/console/controller/balance/simple.go
@@ -7,6 +7,7 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/balance"
)
+//GetSimpleList 获取简易列表
func GetSimpleList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationLoadBalance, controller.OperationREAD)
if e != nil {
diff --git a/console/controller/cluster/cluster.go b/console/controller/cluster/cluster.go
index bd3c15d..eeab4fe 100644
--- a/console/controller/cluster/cluster.go
+++ b/console/controller/cluster/cluster.go
@@ -7,6 +7,7 @@ import (
cluster2 "github.com/eolinker/goku-api-gateway/server/cluster"
)
+//GetClusterList 获取集群列表
func GetClusterList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationREAD)
if e != nil {
@@ -21,6 +22,7 @@ func GetClusterList(httpResponse http.ResponseWriter, httpRequest *http.Request)
}
+//GetClusterInfoList 获取集群信息列表
func GetClusterInfoList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationREAD)
diff --git a/console/controller/config-log/access.go b/console/controller/config-log/access.go
index 387b5e0..c3c8bff 100644
--- a/console/controller/config-log/access.go
+++ b/console/controller/config-log/access.go
@@ -1,4 +1,4 @@
-package config_log
+package configlog
import (
"fmt"
@@ -9,6 +9,7 @@ import (
module "github.com/eolinker/goku-api-gateway/console/module/config-log"
)
+//AccessLogHandler access日志处理器
type AccessLogHandler struct {
}
diff --git a/console/controller/config-log/handle.go b/console/controller/config-log/handle.go
index fab769c..ff5f79a 100644
--- a/console/controller/config-log/handle.go
+++ b/console/controller/config-log/handle.go
@@ -1,4 +1,4 @@
-package config_log
+package configlog
import (
"fmt"
@@ -7,6 +7,7 @@ import (
"strings"
)
+//Handle 处理器
func Handle(prefix string) http.Handler {
pre := strings.TrimSuffix(prefix, "/")
@@ -21,9 +22,7 @@ func Handle(prefix string) http.Handler {
}
serveMux.Handle(fmt.Sprintf("%s/%s", pre, "node"), nodeLogHandler)
- accessLogHandler := &AccessLogHandler{
-
- }
+ accessLogHandler := &AccessLogHandler{}
serveMux.Handle(fmt.Sprintf("%s/%s", pre, "access"), accessLogHandler)
diff --git a/console/controller/config-log/log.go b/console/controller/config-log/log.go
index f334f99..2a88018 100644
--- a/console/controller/config-log/log.go
+++ b/console/controller/config-log/log.go
@@ -1,4 +1,4 @@
-package config_log
+package configlog
import (
"fmt"
@@ -9,6 +9,7 @@ import (
module "github.com/eolinker/goku-api-gateway/console/module/config-log"
)
+//LogHandler 日志处理器
type LogHandler struct {
name string
}
diff --git a/console/controller/discovery/handle.go b/console/controller/discovery/handle.go
index d77a55c..1b7a410 100644
--- a/console/controller/discovery/handle.go
+++ b/console/controller/discovery/handle.go
@@ -4,6 +4,7 @@ import (
"net/http"
)
+//Handle 处理器
func Handle(prefix string) http.Handler {
serveMux := http.NewServeMux()
diff --git a/console/controller/gateway/gateway.go b/console/controller/gateway/gateway.go
index 670bb37..7116285 100644
--- a/console/controller/gateway/gateway.go
+++ b/console/controller/gateway/gateway.go
@@ -9,6 +9,7 @@ import (
monitor_read "github.com/eolinker/goku-api-gateway/server/monitor/monitor-read"
)
+//GetGatewayConfig 获取网关配置
func GetGatewayConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationGatewayConfig, controller.OperationREAD)
if e != nil {
@@ -30,6 +31,7 @@ func GetGatewayConfig(httpResponse http.ResponseWriter, httpRequest *http.Reques
return
}
+//EditGatewayBaseConfig 获取网关基本配置
func EditGatewayBaseConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationGatewayConfig, controller.OperationEDIT)
if e != nil {
@@ -94,6 +96,7 @@ func EditGatewayBaseConfig(httpResponse http.ResponseWriter, httpRequest *http.R
return
}
+//EditGatewayAlarmConfig 编辑网关告警配置
func EditGatewayAlarmConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationGatewayConfig, controller.OperationEDIT)
if e != nil {
diff --git a/console/controller/monitor/gateway.go b/console/controller/monitor/gateway.go
index f4b9995..9385db5 100644
--- a/console/controller/monitor/gateway.go
+++ b/console/controller/monitor/gateway.go
@@ -11,6 +11,7 @@ import (
"github.com/eolinker/goku-api-gateway/server/cluster"
)
+//GetGatewayMonitorSummaryByPeriod 获取网关概况
func GetGatewayMonitorSummaryByPeriod(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNone, controller.OperationREAD)
if e != nil {
@@ -18,7 +19,7 @@ func GetGatewayMonitorSummaryByPeriod(httpResponse http.ResponseWriter, httpRequ
}
clusterName := httpRequest.PostFormValue("cluster")
- clusterId, has := cluster.GetId(clusterName)
+ clusterID, has := cluster.GetID(clusterName)
if !has && clusterName != "" {
controller.WriteError(httpResponse, "340003", "", "[ERROR]Illegal cluster!", nil)
return
@@ -60,7 +61,7 @@ func GetGatewayMonitorSummaryByPeriod(httpResponse http.ResponseWriter, httpRequ
return
}
- flag, result, err := monitor.GetGatewayMonitorSummaryByPeriod(clusterId, beginTime, endTime, p)
+ flag, result, err := monitor.GetGatewayMonitorSummaryByPeriod(clusterID, beginTime, endTime, p)
if !flag {
controller.WriteError(httpResponse,
"340000",
diff --git a/console/controller/node/node.go b/console/controller/node/node.go
index 5462a12..f88b8d4 100644
--- a/console/controller/node/node.go
+++ b/console/controller/node/node.go
@@ -15,7 +15,7 @@ import (
"github.com/eolinker/goku-api-gateway/utils"
)
-// 新增节点信息
+//AddNode 新增节点信息
func AddNode(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationEDIT)
@@ -25,7 +25,7 @@ func AddNode(httpResponse http.ResponseWriter, httpRequest *http.Request) {
cluserName := httpRequest.PostFormValue("cluster")
- clusterId, has := cluster2.GetId(cluserName)
+ clusterID, has := cluster2.GetID(cluserName)
if !has {
controller.WriteError(httpResponse, "340003", "", "[ERROR]Illegal cluster!", nil)
return
@@ -79,7 +79,7 @@ func AddNode(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
- flag, result, err := node.AddNode(clusterId, nodeName, nodeIP, nodePort, gatewayPath, gID)
+ flag, result, err := node.AddNode(clusterID, nodeName, nodeIP, nodePort, gatewayPath, gID)
if !flag {
controller.WriteError(httpResponse,
@@ -102,7 +102,7 @@ func AddNode(httpResponse http.ResponseWriter, httpRequest *http.Request) {
httpResponse.Write(data)
}
-// 修改节点信息
+//EditNode 修改节点信息
func EditNode(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationEDIT)
@@ -122,7 +122,7 @@ func EditNode(httpResponse http.ResponseWriter, httpRequest *http.Request) {
flag := utils.ValidateRemoteAddr(nodeIP + ":" + nodePort)
if !flag {
- controller.WriteError(httpResponse, "230006", "node", "[ERROR]Illegal remote address!", errors.New("[ERROR]Illegal remote address!"))
+ controller.WriteError(httpResponse, "230006", "node", "[ERROR]Illegal remote address!", errors.New("[error]illegal remote address"))
return
}
@@ -172,7 +172,7 @@ func EditNode(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 删除节点信息
+//DeleteNode 删除节点信息
func DeleteNode(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationEDIT)
@@ -228,7 +228,7 @@ func GetNodeList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
gID = -1
}
- clusterID, has := cluster2.GetId(cluserName)
+ clusterID, has := cluster2.GetID(cluserName)
if !has {
controller.WriteError(httpResponse, "330003", "node", "[ERROR]The cluster dosen't exist!", nil)
return
@@ -249,7 +249,7 @@ func GetNodeList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
}
-// 获取节点信息
+//GetNodeInfo 获取节点信息
func GetNodeInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationREAD)
if e != nil {
@@ -285,7 +285,7 @@ func GetNodeInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 节点IP查重
+//CheckIsExistRemoteAddr 节点IP查重
func CheckIsExistRemoteAddr(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationREAD)
@@ -323,7 +323,7 @@ func CheckIsExistRemoteAddr(httpResponse http.ResponseWriter, httpRequest *http.
return
}
-// 批量修改节点分组
+//BatchEditNodeGroup 批量修改节点分组
func BatchEditNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationEDIT)
@@ -361,7 +361,7 @@ func BatchEditNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Requ
return
}
-// 批量删除节点
+//BatchDeleteNode 批量删除节点
func BatchDeleteNode(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationEDIT)
diff --git a/console/controller/node/nodeGroup.go b/console/controller/node/nodeGroup.go
index 2177d20..d72acf5 100644
--- a/console/controller/node/nodeGroup.go
+++ b/console/controller/node/nodeGroup.go
@@ -9,6 +9,7 @@ import (
cluster2 "github.com/eolinker/goku-api-gateway/server/cluster"
)
+//AddNodeGroup 新增节点分组
func AddNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationEDIT)
@@ -18,7 +19,7 @@ func AddNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
cluserName := httpRequest.PostFormValue("cluster")
- clusterId, has := cluster2.GetId(cluserName)
+ clusterID, has := cluster2.GetID(cluserName)
if !has {
controller.WriteError(httpResponse, "340003", "", "[ERROR]Illegal cluster!", nil)
@@ -34,7 +35,7 @@ func AddNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
- flag, result, err := node.AddNodeGroup(groupName, clusterId)
+ flag, result, err := node.AddNodeGroup(groupName, clusterID)
if !flag {
controller.WriteError(httpResponse,
@@ -50,7 +51,7 @@ func AddNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 修改节点分组信息
+//EditNodeGroup 修改节点分组信息
func EditNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationEDIT)
@@ -95,7 +96,7 @@ func EditNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request)
controller.WriteResultInfo(httpResponse, "nodeGroup", "", nil)
}
-// 删除节点分组
+//DeleteNodeGroup 删除节点分组
func DeleteNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationEDIT)
if e != nil {
@@ -147,7 +148,7 @@ func DeleteNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request
}
-// 获取节点分组信息
+//GetNodeGroupInfo 获取节点分组信息
func GetNodeGroupInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationREAD)
if e != nil {
@@ -180,7 +181,7 @@ func GetNodeGroupInfo(httpResponse http.ResponseWriter, httpRequest *http.Reques
controller.WriteResultInfo(httpResponse, "node", "groupInfo", result)
}
-// 获取节点分组列表
+//GetNodeGroupList 获取节点分组列表
func GetNodeGroupList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationNode, controller.OperationREAD)
if e != nil {
@@ -188,7 +189,7 @@ func GetNodeGroupList(httpResponse http.ResponseWriter, httpRequest *http.Reques
}
cluserName := httpRequest.FormValue("cluster")
- clusterId, has := cluster2.GetId(cluserName)
+ clusterID, has := cluster2.GetID(cluserName)
if !has {
controller.WriteError(httpResponse,
"280001",
@@ -197,7 +198,7 @@ func GetNodeGroupList(httpResponse http.ResponseWriter, httpRequest *http.Reques
nil)
return
}
- flag, result, err := node.GetNodeGroupList(clusterId)
+ flag, result, err := node.GetNodeGroupList(clusterID)
if !flag {
controller.WriteError(httpResponse,
diff --git a/console/controller/plugin/plugin.go b/console/controller/plugin/plugin.go
index 9fa5ba4..0a42ca3 100644
--- a/console/controller/plugin/plugin.go
+++ b/console/controller/plugin/plugin.go
@@ -40,7 +40,7 @@ func GetPluginList(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 新增插件信息
+//AddPlugin 新增插件信息
func AddPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
@@ -106,7 +106,7 @@ func AddPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 修改插件信息
+//EditPlugin 修改插件信息
func EditPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
@@ -162,7 +162,7 @@ func EditPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
controller.WriteResultInfo(httpResponse, "plugin", "", nil)
}
-// 删除插件信息
+//DeletePlugin 删除插件信息
func DeletePlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
@@ -195,7 +195,7 @@ func DeletePlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 获取插件信息
+//GetPluginInfo 获取插件信息
func GetPluginInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationREAD)
if e != nil {
@@ -228,7 +228,7 @@ func GetPluginInfo(httpResponse http.ResponseWriter, httpRequest *http.Request)
controller.WriteResultInfo(httpResponse, "plugin", "pluginInfo", result)
}
-// 获取插件配置
+//GetPluginConfig 获取插件配置
func GetPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationREAD)
if e != nil {
@@ -252,7 +252,7 @@ func GetPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Request
return
}
-// 判断插件优先级是否存在
+//CheckIndexIsExist 判断插件优先级是否存在
func CheckIndexIsExist(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
@@ -286,7 +286,7 @@ func CheckIndexIsExist(httpResponse http.ResponseWriter, httpRequest *http.Reque
return
}
-// 检查插件名称是否存在
+//CheckNameIsExist 检查插件名称是否存在
func CheckNameIsExist(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
@@ -309,7 +309,7 @@ func CheckNameIsExist(httpResponse http.ResponseWriter, httpRequest *http.Reques
}
-// 开启插件
+//StartPlugin 开启插件
func StartPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
@@ -332,7 +332,7 @@ func StartPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
controller.WriteResultInfo(httpResponse, "plugin", "", nil)
}
-// 关闭插件
+//StopPlugin 关闭插件
func StopPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
@@ -354,7 +354,7 @@ func StopPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
controller.WriteResultInfo(httpResponse, "plugin", "", nil)
}
-// 获取不同类型的插件列表
+//GetPluginListByPluginType 获取不同类型的插件列表
func GetPluginListByPluginType(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationREAD)
if e != nil {
@@ -387,7 +387,7 @@ func GetPluginListByPluginType(httpResponse http.ResponseWriter, httpRequest *ht
controller.WriteResultInfo(httpResponse, "plugin", "pluginList", result)
}
-// 批量关闭插件
+//BatchStopPlugin 批量关闭插件
func BatchStopPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
@@ -411,7 +411,7 @@ func BatchStopPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request
return
}
-// 批量关闭插件
+//BatchStartPlugin 批量关闭插件
func BatchStartPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
@@ -435,6 +435,7 @@ func BatchStartPlugin(httpResponse http.ResponseWriter, httpRequest *http.Reques
}
+//CheckPluginIsAvailable 判断插件是否可用
func CheckPluginIsAvailable(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationPlugin, controller.OperationEDIT)
if e != nil {
diff --git a/console/controller/project/project.go b/console/controller/project/project.go
index 0d47c08..675f599 100644
--- a/console/controller/project/project.go
+++ b/console/controller/project/project.go
@@ -8,7 +8,7 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/project"
)
-// 新建项目
+//AddProject 新建项目
func AddProject(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
@@ -41,7 +41,7 @@ func AddProject(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 修改项目信息
+//EditProject 修改项目信息
func EditProject(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
@@ -85,7 +85,7 @@ func EditProject(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 删除项目信息
+//DeleteProject 删除项目信息
func DeleteProject(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
@@ -120,7 +120,7 @@ func DeleteProject(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 删除项目信息
+//BatchDeleteProject 删除项目信息
func BatchDeleteProject(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationEDIT)
if e != nil {
@@ -145,7 +145,7 @@ func BatchDeleteProject(httpResponse http.ResponseWriter, httpRequest *http.Requ
return
}
-// 获取项目信息
+//GetProjectInfo 获取项目信息
func GetProjectInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
@@ -179,7 +179,7 @@ func GetProjectInfo(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 获取项目列表
+//GetProjectList 获取项目列表
func GetProjectList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
@@ -205,14 +205,14 @@ func GetProjectList(httpResponse http.ResponseWriter, httpRequest *http.Request)
return
}
-// 获取项目列表中没有被策略组绑定的接口
-func GetApiListFromProjectNotInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAPIListFromProjectNotInStrategy 获取项目列表中没有被策略组绑定的接口
+func GetAPIListFromProjectNotInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationAPI, controller.OperationREAD)
if e != nil {
return
}
- flag, result, err := project.GetApiListFromProjectNotInStrategy()
+ flag, result, err := project.GetAPIListFromProjectNotInStrategy()
if !flag {
controller.WriteError(httpResponse,
diff --git a/console/controller/script/script.go b/console/controller/script/script.go
index c5215a2..96a3f8e 100644
--- a/console/controller/script/script.go
+++ b/console/controller/script/script.go
@@ -10,8 +10,8 @@ import (
var initTables = []string{"goku_gateway", "goku_plugin", "goku_balance", "goku_gateway_api", "goku_gateway_strategy", "goku_conn_plugin_strategy", "goku_conn_plugin_api", "goku_conn_strategy_api"}
-// 新建项目
-func RefreshApiInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//RefreshAPIInfo 新建项目
+func RefreshAPIInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) {
hashCode := httpRequest.PostFormValue("hashCode")
if hashCode != "cf70df9de35d556cb5eea88e422ec6cb" {
@@ -19,7 +19,7 @@ func RefreshApiInfo(httpResponse http.ResponseWriter, httpRequest *http.Request)
controller.WriteError(httpResponse, "800000", "script", "[Error] Illegal hashCode", nil)
return
}
- if !script.RefreshApiInfo() {
+ if !script.RefreshAPIInfo() {
controller.WriteError(httpResponse, "800000", "script", "[Error] Fail to refresh!", nil)
@@ -28,7 +28,7 @@ func RefreshApiInfo(httpResponse http.ResponseWriter, httpRequest *http.Request)
controller.WriteResultInfo(httpResponse, "script", "", nil)
}
-// 刷新网关告警信息
+//RefreshGatewayAlertConfig 刷新网关告警信息
func RefreshGatewayAlertConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
hashCode := httpRequest.PostFormValue("hashCode")
@@ -46,6 +46,7 @@ func RefreshGatewayAlertConfig(httpResponse http.ResponseWriter, httpRequest *ht
controller.WriteResultInfo(httpResponse, "script", "", nil)
}
+//UpdateTables 更新表
func UpdateTables() {
script.UpdateTables(initTables)
}
diff --git a/console/controller/strategy/apiStrategy.go b/console/controller/strategy/apiStrategy.go
index d38c394..126e815 100644
--- a/console/controller/strategy/apiStrategy.go
+++ b/console/controller/strategy/apiStrategy.go
@@ -11,8 +11,8 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/strategy"
)
-// 将接口加入策略组
-func AddApiToStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//AddAPIToStrategy 将接口加入策略组
+func AddAPIToStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
return
@@ -32,7 +32,7 @@ func AddApiToStrategy(httpResponse http.ResponseWriter, httpRequest *http.Reques
return
}
- flag, result, err := api.AddApiToStrategy(apiArray, strategyID)
+ flag, result, err := api.AddAPIToStrategy(apiArray, strategyID)
if !flag {
controller.WriteError(httpResponse,
"240000",
@@ -47,8 +47,8 @@ func AddApiToStrategy(httpResponse http.ResponseWriter, httpRequest *http.Reques
}
-// ResetApiTargetOfStrategy 将接口加入策略组
-func ResetApiTargetOfStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+// ResetAPITargetOfStrategy 将接口加入策略组
+func ResetAPITargetOfStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
return
@@ -57,7 +57,7 @@ func ResetApiTargetOfStrategy(httpResponse http.ResponseWriter, httpRequest *htt
strategyID := httpRequest.PostFormValue("strategyID")
target := httpRequest.PostFormValue("target")
apiID := httpRequest.PostFormValue("apiID")
- apiId, err := strconv.Atoi(apiID)
+ id, err := strconv.Atoi(apiID)
if err != nil {
controller.WriteError(httpResponse,
"240013",
@@ -77,7 +77,7 @@ func ResetApiTargetOfStrategy(httpResponse http.ResponseWriter, httpRequest *htt
return
}
- flag, result, err := api.SetTarget(apiId, strategyID, target)
+ flag, result, err := api.SetTarget(id, strategyID, target)
if !flag {
controller.WriteError(httpResponse,
"240000",
@@ -91,8 +91,8 @@ func ResetApiTargetOfStrategy(httpResponse http.ResponseWriter, httpRequest *htt
}
-// BatchResetApiTargetOfStrategy 将接口加入策略组
-func BatchResetApiTargetOfStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+// BatchResetAPITargetOfStrategy 将接口加入策略组
+func BatchResetAPITargetOfStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
return
@@ -192,8 +192,8 @@ func GetAPIIDListFromStrategy(httpResponse http.ResponseWriter, httpRequest *htt
return
}
-// GetApiListFromStrategy 获取策略组接口列表
-func GetApiListFromStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+// GetAPIListFromStrategy 获取策略组接口列表
+func GetAPIListFromStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationREAD)
if e != nil {
return
@@ -273,8 +273,8 @@ func GetApiListFromStrategy(httpResponse http.ResponseWriter, httpRequest *http.
return
}
-// 检查插件是否添加进策略组
-func CheckIsExistApiInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//CheckIsExistAPIInStrategy 检查插件是否添加进策略组
+func CheckIsExistAPIInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
return
@@ -293,7 +293,7 @@ func CheckIsExistApiInStrategy(httpResponse http.ResponseWriter, httpRequest *ht
return
}
- flag, _, err := api.CheckIsExistApiInStrategy(id, strategyID)
+ flag, _, err := api.CheckIsExistAPIInStrategy(id, strategyID)
if !flag {
controller.WriteError(httpResponse,
"240000",
@@ -349,8 +349,8 @@ func GetAPIIDListNotInStrategyByProject(httpResponse http.ResponseWriter, httpRe
return
}
-// 获取未被该策略组绑定的接口列表
-func GetApiListNotInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//GetAPIListNotInStrategy 获取未被该策略组绑定的接口列表
+func GetAPIListNotInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationREAD)
if e != nil {
return
@@ -404,8 +404,8 @@ func GetApiListNotInStrategy(httpResponse http.ResponseWriter, httpRequest *http
return
}
-// 批量删除策略组接口
-func BatchDeleteApiInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
+//BatchDeleteAPIInStrategy 批量删除策略组接口
+func BatchDeleteAPIInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
return
@@ -414,7 +414,7 @@ func BatchDeleteApiInStrategy(httpResponse http.ResponseWriter, httpRequest *htt
apiIDList := httpRequest.PostFormValue("apiIDList")
strategyID := httpRequest.PostFormValue("strategyID")
- flag, result, err := api.BatchDeleteApiInStrategy(apiIDList, strategyID)
+ flag, result, err := api.BatchDeleteAPIInStrategy(apiIDList, strategyID)
if !flag {
controller.WriteError(httpResponse,
diff --git a/console/controller/strategy/strategy.go b/console/controller/strategy/strategy.go
index 53041f4..4f1b114 100644
--- a/console/controller/strategy/strategy.go
+++ b/console/controller/strategy/strategy.go
@@ -9,7 +9,7 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// 新增策略组
+//AddStrategy 新增策略组
func AddStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -52,7 +52,7 @@ func AddStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
return
}
-// 修改策略组信息
+//EditStrategy 修改策略组信息
func EditStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -93,7 +93,7 @@ func EditStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
controller.WriteResultInfo(httpResponse, "strategy", "strategyID", result)
}
-// 删除策略组
+//DeleteStrategy 删除策略组
func DeleteStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -137,7 +137,7 @@ func GetOpenStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request
controller.WriteResultInfo(httpResponse, "strategy", "strategyInfo", result)
}
-// 获取策略组列表
+//GetStrategyList 获取策略组列表
func GetStrategyList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationREAD)
if e != nil {
@@ -230,7 +230,7 @@ func GetStrategyInfo(httpResponse http.ResponseWriter, httpRequest *http.Request
controller.WriteResultInfo(httpResponse, "strategy", "strategyInfo", result)
}
-// 批量修改策略组分组
+//BatchEditStrategyGroup 批量修改策略组分组
func BatchEditStrategyGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -272,7 +272,7 @@ func BatchEditStrategyGroup(httpResponse http.ResponseWriter, httpRequest *http.
return
}
-// 批量修改策略组
+//BatchDeleteStrategy 批量修改策略组
func BatchDeleteStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -301,7 +301,7 @@ func BatchDeleteStrategy(httpResponse http.ResponseWriter, httpRequest *http.Req
controller.WriteResultInfo(httpResponse, "strategy", "", nil)
}
-// 更新策略启用状态
+//BatchStartStrategy 更新策略启用状态
func BatchStartStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -330,7 +330,7 @@ func BatchStartStrategy(httpResponse http.ResponseWriter, httpRequest *http.Requ
controller.WriteResultInfo(httpResponse, "strategy", "", nil)
}
-// 更新策略启用状态
+//BatchStopStrategy 更新策略启用状态
func BatchStopStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
diff --git a/console/controller/strategy/strategyPlugin.go b/console/controller/strategy/strategyPlugin.go
index 0095951..06db4a3 100644
--- a/console/controller/strategy/strategyPlugin.go
+++ b/console/controller/strategy/strategyPlugin.go
@@ -10,7 +10,7 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/strategy"
)
-// 新增插件到接口
+//AddPluginToStrategy 新增插件到接口
func AddPluginToStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -67,7 +67,7 @@ func AddPluginToStrategy(httpResponse http.ResponseWriter, httpRequest *http.Req
}
-// 修改插件信息
+//EditStrategyPluginConfig 修改插件信息
func EditStrategyPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -109,7 +109,7 @@ func EditStrategyPluginConfig(httpResponse http.ResponseWriter, httpRequest *htt
}
-// 获取策略组插件列表
+//GetStrategyPluginList 获取策略组插件列表
func GetStrategyPluginList(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationREAD)
if e != nil {
@@ -139,7 +139,7 @@ func GetStrategyPluginList(httpResponse http.ResponseWriter, httpRequest *http.R
controller.WriteResultInfo(httpResponse, "strategyPlugin", "strategyPluginList", result)
}
-// 获取策略组插件信息
+//GetStrategyPluginConfig 获取策略组插件信息
func GetStrategyPluginConfig(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationREAD)
if e != nil {
@@ -154,7 +154,7 @@ func GetStrategyPluginConfig(httpResponse http.ResponseWriter, httpRequest *http
}
-// 检查策略组是否绑定插件
+//CheckPluginIsExistInStrategy 检查策略组是否绑定插件
func CheckPluginIsExistInStrategy(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationREAD)
if e != nil {
@@ -188,7 +188,7 @@ func CheckPluginIsExistInStrategy(httpResponse http.ResponseWriter, httpRequest
controller.WriteResultInfo(httpResponse, "strategyPlugin", "", nil)
}
-// 检查策略组插件是否开启
+//GetStrategyPluginStatus 检查策略组插件是否开启
func GetStrategyPluginStatus(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationREAD)
if e != nil {
@@ -224,7 +224,7 @@ func GetStrategyPluginStatus(httpResponse http.ResponseWriter, httpRequest *http
}
-// 批量开启策略组插件
+//BatchStartStrategyPlugin 批量开启策略组插件
func BatchStartStrategyPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -254,7 +254,7 @@ func BatchStartStrategyPlugin(httpResponse http.ResponseWriter, httpRequest *htt
controller.WriteResultInfo(httpResponse, "strategyPlugin", "", nil)
}
-// 批量修改策略组插件状态
+//BatchStopStrategyPlugin 批量修改策略组插件状态
func BatchStopStrategyPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -283,7 +283,7 @@ func BatchStopStrategyPlugin(httpResponse http.ResponseWriter, httpRequest *http
controller.WriteResultInfo(httpResponse, "strategyPlugin", "", nil)
}
-// 批量删除策略组插件
+//BatchDeleteStrategyPlugin 批量删除策略组插件
func BatchDeleteStrategyPlugin(httpResponse http.ResponseWriter, httpRequest *http.Request) {
_, e := controller.CheckLogin(httpResponse, httpRequest, controller.OperationStrategy, controller.OperationEDIT)
if e != nil {
@@ -314,6 +314,7 @@ func BatchDeleteStrategyPlugin(httpResponse http.ResponseWriter, httpRequest *ht
controller.WriteResultInfo(httpResponse, "strategyPlugin", "", nil)
}
+//UpdateAllStrategyPluginUpdateTag 更新所有策略插件标志位
func UpdateAllStrategyPluginUpdateTag() error {
return strategy.UpdateAllStrategyPluginUpdateTag()
}
diff --git a/console/controller/utils.go b/console/controller/utils.go
index 926054b..fe91223 100644
--- a/console/controller/utils.go
+++ b/console/controller/utils.go
@@ -13,21 +13,33 @@ import (
)
const (
+ //OperationEDIT edit权限
OperationEDIT = "edit"
+ //OperationREAD read权限
OperationREAD = "read"
)
const (
- OperationNone = ""
- OperationAPI = "apiManagement"
- OperationADMIN = "adminManagement"
- OperationLoadBalance = "loadBalance"
- OperationStrategy = "strategyManagement"
- OperationNode = "nodeManagement"
- OperationPlugin = "pluginManagement"
+ //OperationNone none
+ OperationNone = ""
+ //OperationAPI api
+ OperationAPI = "apiManagement"
+ //OperationADMIN admin
+ OperationADMIN = "adminManagement"
+ //OperationLoadBalance balance
+ OperationLoadBalance = "loadBalance"
+ //OperationStrategy strategy
+ OperationStrategy = "strategyManagement"
+ //OperationNode node
+ OperationNode = "nodeManagement"
+ //OperationPlugin plugin
+ OperationPlugin = "pluginManagement"
+ //OperationGatewayConfig gatewayConfig
OperationGatewayConfig = "gatewayConfig"
- OperationAlert = "alertManagement"
+ //OperationAlert alert
+ OperationAlert = "alertManagement"
)
+//PageInfo pageInfo
type PageInfo struct {
ItemNum int `json:"itemNum,"`
Page int `json:"page,omitempty"`
@@ -35,17 +47,22 @@ type PageInfo struct {
TotalNum int `json:"totalNum,"`
}
+//SetPage 设置页码信息
func (p *PageInfo) SetPage(page, size, total int) *PageInfo {
p.Page = page
p.PageSize = size
p.TotalNum = total
return p
}
+
+//NewItemNum 创建pageInfo对象
func NewItemNum(num int) *PageInfo {
return &PageInfo{
ItemNum: num,
}
}
+
+//WriteResult 输出返回结果
func WriteResult(w http.ResponseWriter, code string, resultType, resultKey string, result interface{}, pageInfo *PageInfo) {
ret := map[string]interface{}{
"statusCode": code,
@@ -74,9 +91,13 @@ func WriteResult(w http.ResponseWriter, code string, resultType, resultKey strin
log.WithFields(ret).Debug("write :", i)
}
}
+
+//WriteResultInfoWithPage 输出带页码信息的返回
func WriteResultInfoWithPage(w http.ResponseWriter, resultType, resultKey string, result interface{}, pageInfo *PageInfo) {
WriteResult(w, "000000", resultType, resultKey, result, pageInfo)
}
+
+//WriteResultInfo 输出结果信息
func WriteResultInfo(w http.ResponseWriter, resultType string, resultKey string, result interface{}) {
if result != nil {
@@ -88,9 +109,13 @@ func WriteResultInfo(w http.ResponseWriter, resultType string, resultKey string,
}
WriteResultInfoWithPage(w, resultType, resultKey, result, nil)
}
+
+//WriteResultInfoWithCode 输出带状态码的信息
func WriteResultInfoWithCode(w http.ResponseWriter, code string, resultType, resultKey string, result interface{}) {
WriteResult(w, code, resultType, resultKey, result, nil)
}
+
+//WriteError 输出错误
func WriteError(w http.ResponseWriter, statusCode, resultType, resultDesc string, resuleErr error) {
ret := map[string]interface{}{
@@ -114,23 +139,25 @@ func WriteError(w http.ResponseWriter, statusCode, resultType, resultDesc string
}
+//CheckLogin 检查登录
func CheckLogin(w http.ResponseWriter, r *http.Request, operationType, operation string) (int, error) {
userIDCookie, idErr := r.Cookie("userID")
userCookie, userErr := r.Cookie("userToken")
if idErr != nil || userErr != nil {
- e := errors.New("User not logged in!")
+
+ e := errors.New("user not logged in")
WriteError(w, "100001", "user", e.Error(), e)
return 0, e
}
userID, err := strconv.Atoi(userIDCookie.Value)
if err != nil {
- WriteError(w, "100001", "user", "Illegal user Id!", err)
+ WriteError(w, "100001", "user", "Illegal user ID!", err)
return 0, err
}
flag := account.CheckLogin(userCookie.Value, userID)
if !flag {
- e := errors.New("Illegal users!")
+ e := errors.New("illegal users")
WriteError(w, "100001", "user", "Illegal users!", e)
return userID, e
}
diff --git a/console/databse.go b/console/databse.go
index f2f9977..708011d 100644
--- a/console/databse.go
+++ b/console/databse.go
@@ -6,12 +6,15 @@ import (
"github.com/eolinker/goku-api-gateway/server/entity"
)
+//ClusterDatabaseConfig 集群数据库对象
type ClusterDatabaseConfig entity.ClusterDB
+//GetDriver 获取驱动
func (c *ClusterDatabaseConfig) GetDriver() string {
return c.Driver
}
+//GetSource 获取链接字符串
func (c *ClusterDatabaseConfig) GetSource() string {
//dsn = conf.Value("db_user") + ":" + conf.Value("db_password")
@@ -20,6 +23,7 @@ func (c *ClusterDatabaseConfig) GetSource() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", c.UserName, c.Password, c.Host, c.Port, c.Database)
}
+//InitDatabase 初始化数据库
func InitDatabase() {
def, err := getDefaultDatabase()
if err != nil {
diff --git a/console/log.go b/console/log.go
index 58765be..0f0452c 100644
--- a/console/log.go
+++ b/console/log.go
@@ -5,6 +5,7 @@ import (
log "github.com/eolinker/goku-api-gateway/goku-log"
)
+//InitLog 初始化日志
func InitLog() {
c, _ := module.Get(module.ConsoleLog)
diff --git a/console/module/account/guest.go b/console/module/account/guest.go
index 5288f72..dc526cb 100644
--- a/console/module/account/guest.go
+++ b/console/module/account/guest.go
@@ -4,22 +4,24 @@ import (
"github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
+//Login 登录
func Login(loginCall, loginPassword string) (bool, int) {
- return console_mysql.Login(loginCall, loginPassword)
+ return consolemysql.Login(loginCall, loginPassword)
}
-// 检查用户是否登录
+//CheckLogin 检查用户是否登录
func CheckLogin(userToken string, userID int) bool {
- return console_mysql.CheckLogin(userToken, userID)
+ return consolemysql.CheckLogin(userToken, userID)
}
-// 用户注册
+//Register 用户注册
func Register(loginCall, loginPassword string) bool {
- return console_mysql.Register(loginCall, loginPassword)
+ return consolemysql.Register(loginCall, loginPassword)
}
+//CheckSuperAdminCount 获取超级管理员数量
func CheckSuperAdminCount() (int, error) {
- b, err := console_mysql.CheckSuperAdminCount()
+ b, err := consolemysql.CheckSuperAdminCount()
return b, err
}
diff --git a/console/module/account/user.go b/console/module/account/user.go
index 1ebdf41..c779f4b 100644
--- a/console/module/account/user.go
+++ b/console/module/account/user.go
@@ -4,37 +4,37 @@ import (
"github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
-// 获取具有编辑权限的用户列表
+//GetUserListWithPermission 获取具有编辑权限的用户列表
func GetUserListWithPermission(operationType, operation string) (bool, []map[string]interface{}, error) {
- return console_mysql.GetUserListWithPermission(operationType, operation)
+ return consolemysql.GetUserListWithPermission(operationType, operation)
}
-// 修改账户信息
+//EditPassword 修改账户信息
func EditPassword(oldPassword, newPassword string, userID int) (bool, string, error) {
- return console_mysql.EditPassword(oldPassword, newPassword, userID)
+ return consolemysql.EditPassword(oldPassword, newPassword, userID)
}
-// 获取账户信息
+//GetUserInfo 获取账户信息
func GetUserInfo(userID int) (bool, interface{}, error) {
- return console_mysql.GetUserInfo(userID)
+ return consolemysql.GetUserInfo(userID)
}
-// 获取用户类型
+//GetUserType 获取用户类型
func GetUserType(userID int) (bool, interface{}, error) {
- return console_mysql.GetUserType(userID)
+ return consolemysql.GetUserType(userID)
}
-// 判断是否是管理员
+//CheckUserIsAdmin 判断是否是管理员
func CheckUserIsAdmin(userID int) (bool, string, error) {
- return console_mysql.CheckUserIsAdmin(userID)
+ return consolemysql.CheckUserIsAdmin(userID)
}
-// 判断是否是超级管理员
+//CheckUserIsSuperAdmin 判断是否是超级管理员
func CheckUserIsSuperAdmin(userID int) (bool, string, error) {
- return console_mysql.CheckUserIsSuperAdmin(userID)
+ return consolemysql.CheckUserIsSuperAdmin(userID)
}
-// 检查用户权限
+//CheckUserPermission 检查用户权限
func CheckUserPermission(operationType, operation string, userID int) (bool, string, error) {
- return console_mysql.CheckUserPermission(operationType, operation, userID)
+ return consolemysql.CheckUserPermission(operationType, operation, userID)
}
diff --git a/console/module/alert/alert.go b/console/module/alert/alert.go
index cbcb7bc..0408976 100644
--- a/console/module/alert/alert.go
+++ b/console/module/alert/alert.go
@@ -10,22 +10,22 @@ import (
"github.com/eolinker/goku-api-gateway/utils"
)
-// 获取告警信息列表
+//GetAlertMsgList 获取告警信息列表
func GetAlertMsgList(page, pageSize int) (bool, []map[string]interface{}, int, error) {
return console_mysql.GetAlertMsgList(page, pageSize)
}
-// 清空告警信息列表
+//ClearAlertMsg 清空告警信息列表
func ClearAlertMsg() (bool, string, error) {
return console_mysql.ClearAlertMsg()
}
-// 删除告警信息
+//DeleteAlertMsg 删除告警信息
func DeleteAlertMsg(alertID int) (bool, string, error) {
return console_mysql.DeleteAlertMsg(alertID)
}
-// 新增告警信息
+//AddAlertMsg 新增告警信息
func AddAlertMsg(apiID, apiName, requestURL, targetServer, targetURL, requestMethod, proxyMethod, headerList, queryParamList, formParamList, responseHeaderList, strategyID, strategyName, requestID string, alertPeriodType, alertCount, responseStatus int, isAlert bool, ip, clusterName string) (bool, string, error) {
flag, result, err := console_mysql.GetAlertConfig()
@@ -43,11 +43,11 @@ func AddAlertMsg(apiID, apiName, requestURL, targetServer, targetURL, requestMet
go utils.SendAlertMail(result["sender"].(string), result["senderPassword"].(string), result["smtpAddress"].(string), strconv.Itoa(result["smtpPort"].(int)), strconv.Itoa(result["smtpProtocol"].(int)), apiAlertInfo["receiverList"].(string), requestURL, logConfig.Dir, strconv.Itoa(alertPeriodType), strconv.Itoa(alertCount), apiName, apiID, targetServer, targetURL)
return console_mysql.AddAlertMsg(requestURL, targetServer, targetURL, ip, clusterName, alertPeriodType, alertCount)
- } else {
- return true, "", nil
}
+ return true, "", nil
}
+//GetAlertConfig 获取告警配置
func GetAlertConfig() (bool, map[string]interface{}, error) {
return console_mysql.GetAlertConfig()
}
diff --git a/console/module/alert/log.go b/console/module/alert/log.go
index 80056e3..f79bf46 100644
--- a/console/module/alert/log.go
+++ b/console/module/alert/log.go
@@ -6,7 +6,7 @@ import (
log "github.com/eolinker/goku-api-gateway/goku-log"
)
-// 记录告警日志
+//AlertLog 记录告警日志
func AlertLog(requestURL, targetServer, targetURL, requestMethod, proxyMethod, headerList, queryParamList, formParamList, responseHeaderList string, responseStatus int, host, strategyID, strategyName, requestID string) {
fields := log.Fields{
diff --git a/console/module/api/api.go b/console/module/api/api.go
index 877bb22..80e1bdc 100644
--- a/console/module/api/api.go
+++ b/console/module/api/api.go
@@ -6,30 +6,30 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// 新增接口
-func AddApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol string, projectID, groupID, timeout, retryCount, alertValve, managerID, userID int) (bool, int, error) {
+//AddAPI 新增接口
+func AddAPI(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol string, projectID, groupID, timeout, retryCount, alertValve, managerID, userID int) (bool, int, error) {
name := "goku_gateway_api"
- flag, result, err := console_mysql.AddApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol, projectID, groupID, timeout, retryCount, alertValve, managerID, userID)
+ flag, result, err := console_mysql.AddAPI(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol, projectID, groupID, timeout, retryCount, alertValve, managerID, userID)
if flag {
dao.UpdateTable(name)
}
return flag, result, err
}
-// 新增接口
-func EditApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol string, projectID, groupID, timeout, retryCount, alertValve, apiID, managerID, userID int) (bool, error) {
+//EditAPI 新增接口
+func EditAPI(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol string, projectID, groupID, timeout, retryCount, alertValve, apiID, managerID, userID int) (bool, error) {
name := "goku_gateway_api"
- flag, err := console_mysql.EditApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol, projectID, groupID, timeout, retryCount, alertValve, apiID, managerID, userID)
+ flag, err := console_mysql.EditAPI(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol, projectID, groupID, timeout, retryCount, alertValve, apiID, managerID, userID)
if flag {
dao.UpdateTable(name)
}
return flag, err
}
-// 获取接口信息
-func GetApiInfo(apiID int) (bool, *entity.Api, error) {
- return console_mysql.GetApiInfo(apiID)
+//GetAPIInfo 获取接口信息
+func GetAPIInfo(apiID int) (bool, *entity.API, error) {
+ return console_mysql.GetAPIInfo(apiID)
}
// GetAPIIDList 获取接口ID列表
@@ -42,27 +42,27 @@ func GetAPIList(projectID int, groupID int, keyword string, condition, page, pag
return console_mysql.GetAPIList(projectID, groupID, keyword, condition, page, pageSize, ids)
}
-// 接口路径是否存在
+//CheckURLIsExist 接口路径是否存在
func CheckURLIsExist(requestURL, requestMethod string, projectID, apiID int) bool {
return console_mysql.CheckURLIsExist(requestURL, requestMethod, projectID, apiID)
}
-// 检查接口是否存在
-func CheckApiIsExist(apiID int) (bool, error) {
- return console_mysql.CheckApiIsExist(apiID)
+//CheckAPIIsExist 检查接口是否存在
+func CheckAPIIsExist(apiID int) (bool, error) {
+ return console_mysql.CheckAPIIsExist(apiID)
}
-// 批量修改接口分组
-func BatchEditApiGroup(apiIDList []string, groupID int) (bool, string, error) {
- r, e := console_mysql.BatchEditApiGroup(apiIDList, groupID)
+//BatchEditAPIGroup 批量修改接口分组
+func BatchEditAPIGroup(apiIDList []string, groupID int) (bool, string, error) {
+ r, e := console_mysql.BatchEditAPIGroup(apiIDList, groupID)
return e == nil, r, e
}
-// 批量修改接口负载
-func BatchEditApiBalance(apiIDList []string, balance string) (string, error) {
+//BatchEditAPIBalance 批量修改接口负载
+func BatchEditAPIBalance(apiIDList []string, balance string) (string, error) {
- r, err := console_mysql.BatchEditApiBalance(apiIDList, balance)
+ r, err := console_mysql.BatchEditAPIBalance(apiIDList, balance)
if err != nil {
name := "goku_gateway_api"
dao.UpdateTable(name)
@@ -70,10 +70,10 @@ func BatchEditApiBalance(apiIDList []string, balance string) (string, error) {
return r, err
}
-// 批量删除接口
-func BatchDeleteApi(apiIDList string) (bool, string, error) {
+//BatchDeleteAPI 批量删除接口
+func BatchDeleteAPI(apiIDList string) (bool, string, error) {
- flag, result, err := console_mysql.BatchDeleteApi(apiIDList)
+ flag, result, err := console_mysql.BatchDeleteAPI(apiIDList)
if flag {
name := "goku_gateway_api"
dao.UpdateTable(name)
diff --git a/console/module/api/apiGroup.go b/console/module/api/apiGroup.go
index 09b7f83..3a4b85a 100644
--- a/console/module/api/apiGroup.go
+++ b/console/module/api/apiGroup.go
@@ -2,22 +2,22 @@ package api
import (
"github.com/eolinker/goku-api-gateway/server/dao"
- console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
+ consolemysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
-// 新建接口分组
-func AddApiGroup(groupName string, projectID, parentGroupID int) (bool, interface{}, error) {
- return console_mysql.AddApiGroup(groupName, projectID, parentGroupID)
+//AddAPIGroup 新建接口分组
+func AddAPIGroup(groupName string, projectID, parentGroupID int) (bool, interface{}, error) {
+ return consolemysql.AddAPIGroup(groupName, projectID, parentGroupID)
}
-// 修改接口分组
-func EditApiGroup(groupName string, groupID, projectID int) (bool, string, error) {
- return console_mysql.EditApiGroup(groupName, groupID, projectID)
+//EditAPIGroup 修改接口分组
+func EditAPIGroup(groupName string, groupID, projectID int) (bool, string, error) {
+ return consolemysql.EditAPIGroup(groupName, groupID, projectID)
}
-// 删除接口分组
-func DeleteApiGroup(projectID, groupID int) (bool, string, error) {
- flag, result, err := console_mysql.DeleteApiGroup(projectID, groupID)
+//DeleteAPIGroup 删除接口分组
+func DeleteAPIGroup(projectID, groupID int) (bool, string, error) {
+ flag, result, err := consolemysql.DeleteAPIGroup(projectID, groupID)
if flag {
dao.UpdateTable("goku_gateway_strategy")
dao.UpdateTable("goku_gateway_api")
@@ -28,11 +28,12 @@ func DeleteApiGroup(projectID, groupID int) (bool, string, error) {
return flag, result, err
}
-// 获取接口分组列表
-func GetApiGroupList(projectID int) (bool, []map[string]interface{}, error) {
- return console_mysql.GetApiGroupList(projectID)
+//GetAPIGroupList 获取接口分组列表
+func GetAPIGroupList(projectID int) (bool, []map[string]interface{}, error) {
+ return consolemysql.GetAPIGroupList(projectID)
}
-func UpdateApiGroupScript() bool {
- return console_mysql.UpdateApiGroupScript()
+//UpdateAPIGroupScript 更新接口分组脚本
+func UpdateAPIGroupScript() bool {
+ return consolemysql.UpdateAPIGroupScript()
}
diff --git a/console/module/api/apiPlugin.go b/console/module/api/apiPlugin.go
index b03ae35..b30d7d9 100644
--- a/console/module/api/apiPlugin.go
+++ b/console/module/api/apiPlugin.go
@@ -8,11 +8,11 @@ import (
console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
-// 批量修改接口插件状态
-func BatchEditApiPluginStatus(connIDList, strategyID string, pluginStatus, userID int) (bool, string, error) {
+//BatchEditAPIPluginStatus 批量修改接口插件状态
+func BatchEditAPIPluginStatus(connIDList, strategyID string, pluginStatus, userID int) (bool, string, error) {
idList := []string{}
plugins := []string{}
- flag, apiIDList, _ := console_mysql.CheckApiPluginIsExistByConnIDList(connIDList, "goku-circuit_breaker")
+ flag, apiIDList, _ := console_mysql.CheckAPIPluginIsExistByConnIDList(connIDList, "goku-circuit_breaker")
if flag {
for _, id := range apiIDList {
idList = append(idList, strconv.Itoa(id))
@@ -20,7 +20,7 @@ func BatchEditApiPluginStatus(connIDList, strategyID string, pluginStatus, userI
plugins = append(plugins, "goku-circuit_breaker")
}
- flag, apiIDList, _ = console_mysql.CheckApiPluginIsExistByConnIDList(connIDList, "goku-proxy_caching")
+ flag, apiIDList, _ = console_mysql.CheckAPIPluginIsExistByConnIDList(connIDList, "goku-proxy_caching")
if flag {
for _, id := range apiIDList {
idList = append(idList, strconv.Itoa(id))
@@ -28,70 +28,71 @@ func BatchEditApiPluginStatus(connIDList, strategyID string, pluginStatus, userI
plugins = append(plugins, "goku-proxy_caching")
}
name := "goku_conn_plugin_api"
- flag, result, err := console_mysql.BatchEditApiPluginStatus(connIDList, strategyID, pluginStatus, userID)
+ flag, result, err := console_mysql.BatchEditAPIPluginStatus(connIDList, strategyID, pluginStatus, userID)
if flag {
dao.UpdateTable(name)
p := strings.Join(plugins, ",")
ids := strings.Join(idList, ",")
- console_mysql.UpdateApiTagByPluginName(strategyID, ids, p)
+ console_mysql.UpdateAPITagByPluginName(strategyID, ids, p)
}
return flag, result, err
}
-// 批量删除接口插件
-func BatchDeleteApiPlugin(connIDList, strategyID string) (bool, string, error) {
+//BatchDeleteAPIPlugin 批量删除接口插件
+func BatchDeleteAPIPlugin(connIDList, strategyID string) (bool, string, error) {
name := "goku_conn_plugin_api"
- flag, result, err := console_mysql.BatchDeleteApiPlugin(connIDList, strategyID)
+ flag, result, err := console_mysql.BatchDeleteAPIPlugin(connIDList, strategyID)
if flag {
dao.UpdateTable(name)
}
return flag, result, err
}
-// 新增插件到接口
-func AddPluginToApi(pluginName, config, strategyID string, apiID, userID int) (bool, interface{}, error) {
+//AddPluginToAPI 新增插件到接口
+func AddPluginToAPI(pluginName, config, strategyID string, apiID, userID int) (bool, interface{}, error) {
name := "goku_conn_plugin_api"
- flag, result, err := console_mysql.AddPluginToApi(pluginName, config, strategyID, apiID, userID)
+ flag, result, err := console_mysql.AddPluginToAPI(pluginName, config, strategyID, apiID, userID)
if flag {
dao.UpdateTable(name)
- console_mysql.UpdateApiTagByPluginName(strategyID, strconv.Itoa(apiID), pluginName)
+ console_mysql.UpdateAPITagByPluginName(strategyID, strconv.Itoa(apiID), pluginName)
}
return flag, result, err
}
-// 修改接口插件配置
-func EditApiPluginConfig(pluginName, config, strategyID string, apiID, userID int) (bool, interface{}, error) {
+//EditAPIPluginConfig 修改接口插件配置
+func EditAPIPluginConfig(pluginName, config, strategyID string, apiID, userID int) (bool, interface{}, error) {
name := "goku_conn_plugin_api"
- flag, result, err := console_mysql.EditApiPluginConfig(pluginName, config, strategyID, apiID, userID)
+ flag, result, err := console_mysql.EditAPIPluginConfig(pluginName, config, strategyID, apiID, userID)
if flag {
dao.UpdateTable(name)
- console_mysql.UpdateApiTagByPluginName(strategyID, strconv.Itoa(apiID), pluginName)
+ console_mysql.UpdateAPITagByPluginName(strategyID, strconv.Itoa(apiID), pluginName)
}
return flag, result, err
}
-func GetApiPluginList(apiID int, strategyID string) (bool, []map[string]interface{}, error) {
- return console_mysql.GetApiPluginList(apiID, strategyID)
+//GetAPIPluginList 获取接口插件列表
+func GetAPIPluginList(apiID int, strategyID string) (bool, []map[string]interface{}, error) {
+ return console_mysql.GetAPIPluginList(apiID, strategyID)
}
-// 获取插件优先级
+//GetPluginIndex 获取插件优先级
func GetPluginIndex(pluginName string) (bool, int, error) {
return console_mysql.GetPluginIndex(pluginName)
}
-// 通过ApiID获取配置信息
-func GetApiPluginConfig(apiID int, strategyID, pluginName string) (bool, map[string]string, error) {
- return console_mysql.GetApiPluginConfig(apiID, strategyID, pluginName)
+//GetAPIPluginConfig 通过APIID获取配置信息
+func GetAPIPluginConfig(apiID int, strategyID, pluginName string) (bool, map[string]string, error) {
+ return console_mysql.GetAPIPluginConfig(apiID, strategyID, pluginName)
}
-// 检查策略组是否绑定插件
-func CheckPluginIsExistInApi(strategyID, pluginName string, apiID int) (bool, error) {
- return console_mysql.CheckPluginIsExistInApi(strategyID, pluginName, apiID)
+//CheckPluginIsExistInAPI 检查策略组是否绑定插件
+func CheckPluginIsExistInAPI(strategyID, pluginName string, apiID int) (bool, error) {
+ return console_mysql.CheckPluginIsExistInAPI(strategyID, pluginName, apiID)
}
-// 获取策略组中所有接口插件列表
-func GetAllApiPluginInStrategy(strategyID string) (bool, []map[string]interface{}, error) {
- return console_mysql.GetAllApiPluginInStrategy(strategyID)
+//GetAllAPIPluginInStrategy 获取策略组中所有接口插件列表
+func GetAllAPIPluginInStrategy(strategyID string) (bool, []map[string]interface{}, error) {
+ return console_mysql.GetAllAPIPluginInStrategy(strategyID)
}
// GetAPIPluginInStrategyByAPIID 获取策略组中所有接口插件列表
@@ -99,10 +100,12 @@ func GetAPIPluginInStrategyByAPIID(strategyID string, apiID int, keyword string,
return console_mysql.GetAPIPluginInStrategyByAPIID(strategyID, apiID, keyword, condition)
}
-func GetApiPluginListWithNotAssignApiList(strategyID string) (bool, []map[string]interface{}, error) {
- return console_mysql.GetApiPluginListWithNotAssignApiList(strategyID)
+//GetAPIPluginListWithNotAssignAPIList 获取没有绑定插件的接口列表
+func GetAPIPluginListWithNotAssignAPIList(strategyID string) (bool, []map[string]interface{}, error) {
+ return console_mysql.GetAPIPluginListWithNotAssignAPIList(strategyID)
}
-func UpdateAllApiPluginUpdateTag() error {
- return console_mysql.UpdateAllApiPluginUpdateTag()
+//UpdateAllAPIPluginUpdateTag 更新所有接口插件更新标识
+func UpdateAllAPIPluginUpdateTag() error {
+ return console_mysql.UpdateAllAPIPluginUpdateTag()
}
diff --git a/console/module/api/apiStrategy.go b/console/module/api/apiStrategy.go
index e547bf7..8f73833 100644
--- a/console/module/api/apiStrategy.go
+++ b/console/module/api/apiStrategy.go
@@ -5,20 +5,20 @@ import (
console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
-// 将接口加入策略组
-func AddApiToStrategy(apiList []string, strategyID string) (bool, string, error) {
+//AddAPIToStrategy 将接口加入策略组
+func AddAPIToStrategy(apiList []string, strategyID string) (bool, string, error) {
name := "goku_conn_strategy_api"
- flag, result, err := console_mysql.AddApiToStrategy(apiList, strategyID)
+ flag, result, err := console_mysql.AddAPIToStrategy(apiList, strategyID)
if flag {
dao.UpdateTable(name)
}
return flag, result, err
}
-// 重置目标地址
-func SetTarget(apiId int, strategyID string, target string) (bool, string, error) {
+//SetTarget 重置目标地址
+func SetTarget(apiID int, strategyID string, target string) (bool, string, error) {
name := "goku_conn_strategy_api"
- flag, result, err := console_mysql.SetApiTargetOfStrategy(apiId, strategyID, target)
+ flag, result, err := console_mysql.SetAPITargetOfStrategy(apiID, strategyID, target)
if flag {
dao.UpdateTable(name)
}
@@ -28,7 +28,7 @@ func SetTarget(apiId int, strategyID string, target string) (bool, string, error
// BatchSetTarget 批量重置目标地址
func BatchSetTarget(apiIds []int, strategyID string, target string) (bool, string, error) {
name := "goku_conn_strategy_api"
- flag, result, err := console_mysql.BatchSetApiTargetOfStrategy(apiIds, strategyID, target)
+ flag, result, err := console_mysql.BatchSetAPITargetOfStrategy(apiIds, strategyID, target)
if flag {
dao.UpdateTable(name)
}
@@ -45,12 +45,12 @@ func GetAPIListFromStrategy(strategyID, keyword string, condition, page, pageSiz
return console_mysql.GetAPIListFromStrategy(strategyID, keyword, condition, page, pageSize, ids, balanceNames)
}
-// 检查插件是否添加进策略组
-func CheckIsExistApiInStrategy(apiID int, strategyID string) (bool, string, error) {
- return console_mysql.CheckIsExistApiInStrategy(apiID, strategyID)
+//CheckIsExistAPIInStrategy 检查插件是否添加进策略组
+func CheckIsExistAPIInStrategy(apiID int, strategyID string) (bool, string, error) {
+ return console_mysql.CheckIsExistAPIInStrategy(apiID, strategyID)
}
-// GetAPIIDListNotInStrategyByProject 获取未被该策略组绑定的接口ID列表(通过项目)
+// GetAPIIDListNotInStrategy 获取未被该策略组绑定的接口ID列表(通过项目)
func GetAPIIDListNotInStrategy(strategyID string, projectID, groupID int, keyword string) (bool, []int, error) {
return console_mysql.GetAPIIDListNotInStrategy(strategyID, projectID, groupID, keyword)
}
@@ -60,10 +60,10 @@ func GetAPIListNotInStrategy(strategyID string, projectID, groupID, page, pageSi
return console_mysql.GetAPIListNotInStrategy(strategyID, projectID, groupID, page, pageSize, keyword)
}
-// 批量删除策略组接口
-func BatchDeleteApiInStrategy(apiIDList, strategyID string) (bool, string, error) {
+//BatchDeleteAPIInStrategy 批量删除策略组接口
+func BatchDeleteAPIInStrategy(apiIDList, strategyID string) (bool, string, error) {
name := "goku_conn_strategy_api"
- flag, result, err := console_mysql.BatchDeleteApiInStrategy(apiIDList, strategyID)
+ flag, result, err := console_mysql.BatchDeleteAPIInStrategy(apiIDList, strategyID)
if flag {
dao.UpdateTable(name)
}
diff --git a/console/module/api/import.go b/console/module/api/import.go
index 1ba768f..a122ca2 100644
--- a/console/module/api/import.go
+++ b/console/module/api/import.go
@@ -6,8 +6,9 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-func ImportApiGroupFromAms(projectID, userID int, groupInfo entity.AmsGroupInfo) (bool, string, error) {
- flag, result, err := console_mysql.ImportApiGroupFromAms(projectID, userID, groupInfo)
+//ImportAPIGroupFromAms 导入接口分组
+func ImportAPIGroupFromAms(projectID, userID int, groupInfo entity.AmsGroupInfo) (bool, string, error) {
+ flag, result, err := console_mysql.ImportAPIGroupFromAms(projectID, userID, groupInfo)
if flag {
name := "goku_gateway_api"
dao.UpdateTable(name)
@@ -15,7 +16,7 @@ func ImportApiGroupFromAms(projectID, userID int, groupInfo entity.AmsGroupInfo)
return flag, result, err
}
-// 导入项目
+//ImportProjectFromAms 导入项目
func ImportProjectFromAms(userID int, projectInfo entity.AmsProject) (bool, string, error) {
flag, result, err := console_mysql.ImportProjectFromAms(userID, projectInfo)
if flag {
@@ -25,9 +26,9 @@ func ImportProjectFromAms(userID int, projectInfo entity.AmsProject) (bool, stri
return flag, result, err
}
-// 导入接口
-func ImportApiFromAms(projectID, groupID, userID int, apiList []entity.AmsApiInfo) (bool, string, error) {
- flag, result, err := console_mysql.ImportApiFromAms(projectID, groupID, userID, apiList)
+//ImportAPIFromAms 导入接口
+func ImportAPIFromAms(projectID, groupID, userID int, apiList []entity.AmsAPIInfo) (bool, string, error) {
+ flag, result, err := console_mysql.ImportAPIFromAms(projectID, groupID, userID, apiList)
if flag {
name := "goku_gateway_api"
dao.UpdateTable(name)
diff --git a/console/module/auth/auth.go b/console/module/auth/auth.go
index 906115b..5d0aac3 100644
--- a/console/module/auth/auth.go
+++ b/console/module/auth/auth.go
@@ -5,17 +5,17 @@ import (
console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
-// 获取认证信息
+//GetAuthStatus 获取认证信息
func GetAuthStatus(strategyID string) (bool, map[string]interface{}, error) {
return console_mysql.GetAuthStatus(strategyID)
}
-// 获取认证信息
+//GetAuthInfo 获取认证信息
func GetAuthInfo(strategyID string) (bool, map[string]interface{}, error) {
return console_mysql.GetAuthInfo(strategyID)
}
-// 编辑认证信息
+//EditAuthInfo 编辑认证信息
func EditAuthInfo(strategyID, strategyName, basicAuthList, apikeyList, jwtCredentialList, oauth2CredentialList string, delClientIDList []string) (bool, error) {
flag, err := console_mysql.EditAuthInfo(strategyID, strategyName, basicAuthList, apikeyList,
jwtCredentialList, oauth2CredentialList, delClientIDList)
diff --git a/console/module/balance/balance.go b/console/module/balance/balance.go
index 54234db..52efa1f 100644
--- a/console/module/balance/balance.go
+++ b/console/module/balance/balance.go
@@ -12,6 +12,7 @@ import (
dao_balance "github.com/eolinker/goku-api-gateway/server/dao/dao-balance"
)
+//Add 新增负载
func Add(info *Param) (string, error) {
const TableName = "goku_balance"
serviceInfo, err := service.Get(info.ServiceName)
@@ -49,6 +50,7 @@ func Add(info *Param) (string, error) {
return "无效serviceName", errors.New("invalid serviceName")
}
+//Save 保存负载
func Save(info *Param) (string, error) {
const TableName = "goku_balance"
serviceInfo, err := service.Get(info.ServiceName)
@@ -85,6 +87,8 @@ func Save(info *Param) (string, error) {
return "无效serviceName", errors.New("invalid serviceName")
}
+
+//Get 获取负载
func Get(name string) (*Info, error) {
b, e := dao_balance.Get(name)
if e != nil {
@@ -93,6 +97,8 @@ func Get(name string) (*Info, error) {
return ReadInfo(b), nil
}
+
+//Search 查询
func Search(keyworkd string) ([]*Info, error) {
var entities []*entity.Balance
if keyworkd == "" {
@@ -116,6 +122,8 @@ func Search(keyworkd string) ([]*Info, error) {
}
return infos, nil
}
+
+//GetAll 获取所有负载信息
func GetAll() ([]*Info, error) {
entities, e := dao_balance.GetAll()
@@ -130,6 +138,7 @@ func GetAll() ([]*Info, error) {
return infos, nil
}
+//Delete 删除
func Delete(name string) (string, error) {
tableName := "goku_balance"
result, err := dao_balance.Delete(name)
@@ -139,11 +148,12 @@ func Delete(name string) (string, error) {
return result, err
}
+//GetBalancNames 获取所有负载名称
func GetBalancNames() (bool, []string, error) {
return dao_balance.GetBalanceNames()
}
-// 批量删除负载
+//BatchDeleteBalance 批量删除负载
func BatchDeleteBalance(balanceNames []string) (string, error) {
tableName := "goku_balance"
result, err := dao_balance.BatchDelete(balanceNames)
diff --git a/console/module/balance/param.go b/console/module/balance/param.go
index a868f7b..5561ab5 100644
--- a/console/module/balance/param.go
+++ b/console/module/balance/param.go
@@ -5,6 +5,7 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/balance-entity-service"
)
+//Param param
type Param struct {
Name string `opt:"balanceName,require"`
ServiceName string `opt:"serviceName,require"`
@@ -14,6 +15,7 @@ type Param struct {
Desc string `opt:"balanceDesc"`
}
+//Info info
type Info struct {
Name string `json:"balanceName"`
ServiceName string `json:"serviceName"`
@@ -27,6 +29,7 @@ type Info struct {
UpdateTime string `json:"updateTime"`
}
+//ReadInfo 读取负载配置
func ReadInfo(balance *entity.Balance) *Info {
info := &Info{
Name: balance.Name,
diff --git a/console/module/balance/update.go b/console/module/balance/update.go
index 684a7c0..fee4dbd 100644
--- a/console/module/balance/update.go
+++ b/console/module/balance/update.go
@@ -10,6 +10,8 @@ import (
func init() {
general.RegeditLater(Update)
}
+
+//Update 更新
func Update() error {
l, e := dao_balance_update.GetAllOldVerSion()
diff --git a/console/module/config-log/get.go b/console/module/config-log/get.go
index 91a4387..d60c190 100644
--- a/console/module/config-log/get.go
+++ b/console/module/config-log/get.go
@@ -1,4 +1,4 @@
-package config_log
+package configlog
import (
"fmt"
@@ -7,6 +7,7 @@ import (
dao "github.com/eolinker/goku-api-gateway/server/dao/config-log"
)
+//Get 获取日志配置
func Get(name string) (*LogConfig, error) {
if _, has := logNames[name]; !has {
return nil, fmt.Errorf("not has that log config of %s", name)
@@ -32,6 +33,7 @@ func Get(name string) (*LogConfig, error) {
return c, nil
}
+//GetAccess 获取access配置
func GetAccess() (*AccessConfig, error) {
config, e := dao.Get(AccessLog)
c := new(AccessConfig)
diff --git a/console/module/config-log/init.go b/console/module/config-log/init.go
index 3569a6e..5043678 100644
--- a/console/module/config-log/init.go
+++ b/console/module/config-log/init.go
@@ -1,5 +1 @@
-package config_log
-
-func InitLog() {
-
-}
+package configlog
diff --git a/console/module/config-log/log.go b/console/module/config-log/log.go
index dcae5fe..adfaee4 100644
--- a/console/module/config-log/log.go
+++ b/console/module/config-log/log.go
@@ -1,4 +1,4 @@
-package config_log
+package configlog
import "C"
import (
@@ -10,9 +10,13 @@ import (
)
const (
- ConsoleLog = "console"
- NodeLog = "node"
- AccessLog = "access"
+ // ConsoleLog 控制台log
+ ConsoleLog = "console"
+ //NodeLog 节点log
+ NodeLog = "node"
+ //AccessLog access log
+ AccessLog = "access"
+ //ExpireDefault 默认过期时间
ExpireDefault = 3
)
@@ -22,6 +26,7 @@ var (
NodeLog: 1,
AccessLog: 1,
}
+ //Expires 过期配置
Expires = []ValueTitle{
{
Value: 3,
@@ -44,6 +49,7 @@ var (
Title: "180天",
},
}
+ //Periods 周期
Periods = []NameTitle{
{
Name: log.PeriodDay.String(),
@@ -54,6 +60,7 @@ var (
Title: "小时",
},
}
+ //Levels 层级
Levels = []NameTitle{
{
Name: log.ErrorLevel.String(),
@@ -73,15 +80,19 @@ var (
}
)
+//NameTitle name title
type NameTitle struct {
Name string `json:"name"`
Title string `json:"title"`
}
+//ValueTitle value title
type ValueTitle struct {
Value int `json:"value"`
Title string `json:"title"`
}
+
+//Param param
type Param struct {
Enable bool
Dir string
@@ -92,6 +103,7 @@ type Param struct {
Expire int
}
+//PutParam put param
type PutParam struct {
Enable bool `opt:"enable,require"`
Dir string `opt:"dir,require"`
@@ -101,6 +113,7 @@ type PutParam struct {
Expire int `opt:"expire,require"`
}
+//Format 格式化
func (p *PutParam) Format() (*Param, error) {
l, err := log.ParseLevel(p.Level)
if err != nil {
@@ -122,6 +135,7 @@ func (p *PutParam) Format() (*Param, error) {
}
+//AccessParam access param
type AccessParam struct {
Enable bool `opt:"enable,require" `
Dir string `opt:"dir,require"`
@@ -131,6 +145,7 @@ type AccessParam struct {
Expire int `opt:"expire,require"`
}
+//Format 格式化
func (p *AccessParam) Format() (*Param, error) {
period, err := log.ParsePeriod(p.Period)
if err != nil {
@@ -147,6 +162,7 @@ func (p *AccessParam) Format() (*Param, error) {
}, nil
}
+//LogConfig 日志配置
type LogConfig struct {
Name string `json:"-"`
Enable bool `json:"enable" opt:"enable" default:"true"`
@@ -174,6 +190,7 @@ func (c *LogConfig) Read(ent *entity.LogConfig) {
}
}
+//AccessConfig access配置
type AccessConfig struct {
Name string `json:"-"`
Enable bool `json:"enable" opt:"enable" default:"true"`
@@ -185,12 +202,15 @@ type AccessConfig struct {
Expires []ValueTitle `json:"expires"`
Fields []*AccessField `json:"fields"`
}
+
+//AccessField access日志字段
type AccessField struct {
Name string `json:"name"`
Select bool `json:"select"`
Desc string `json:"desc"`
}
+//InitFields 初始化字段
func (c *AccessConfig) InitFields() {
// 如果有新增的字段,按默认顺序拼接到末尾
c.Fields = make([]*AccessField, 0, access_field.Size())
diff --git a/console/module/config-log/set.go b/console/module/config-log/set.go
index 34ed345..0d83530 100644
--- a/console/module/config-log/set.go
+++ b/console/module/config-log/set.go
@@ -1,4 +1,4 @@
-package config_log
+package configlog
import (
"fmt"
@@ -8,6 +8,7 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/config-log"
)
+//Set set
func Set(name string, param *Param) error {
if _, has := logNames[name]; !has {
return fmt.Errorf("not has that log config of %s", name)
diff --git a/console/module/gateway/gateway.go b/console/module/gateway/gateway.go
index 2a67fbc..0247376 100644
--- a/console/module/gateway/gateway.go
+++ b/console/module/gateway/gateway.go
@@ -5,11 +5,12 @@ import (
console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
+//GetGatewayConfig 获取网关配置
func GetGatewayConfig() (map[string]interface{}, error) {
return console_mysql.GetGatewayConfig()
}
-// 编辑网关基本配置
+//EditGatewayBaseConfig 编辑网关基本配置
func EditGatewayBaseConfig(successCode string, nodeUpdatePeriod, monitorUpdatePeriod, timeout int) (bool, string, error) {
tableName := "goku_gateway"
flag, result, err := console_mysql.EditGatewayBaseConfig(successCode, nodeUpdatePeriod, monitorUpdatePeriod, timeout)
@@ -19,7 +20,7 @@ func EditGatewayBaseConfig(successCode string, nodeUpdatePeriod, monitorUpdatePe
return flag, result, err
}
-// 编辑网关告警配置
+//EditGatewayAlarmConfig 编辑网关告警配置
func EditGatewayAlarmConfig(apiAlertInfo, sender, senderPassword, smtpAddress string, alertStatus, smtpPort, smtpProtocol int) (bool, string, error) {
tableName := "goku_gateway"
flag, result, err := console_mysql.EditGatewayAlarmConfig(apiAlertInfo, sender, senderPassword, smtpAddress, alertStatus, smtpPort, smtpProtocol)
diff --git a/console/module/monitor/cluster.go b/console/module/monitor/cluster.go
index 3956d5e..3b0ab59 100644
--- a/console/module/monitor/cluster.go
+++ b/console/module/monitor/cluster.go
@@ -6,6 +6,7 @@ import (
monitor_key "github.com/eolinker/goku-api-gateway/server/monitor/monitor-key"
)
+//GatewayRequestInfo 网关请求数量信息
type GatewayRequestInfo struct {
GatewayRequestCount int64 `json:"gatewayRequestCount"`
GatewaySuccessCount int64 `json:"gatewaySuccessCount"`
@@ -28,6 +29,7 @@ func (i *GatewayRequestInfo) read(values monitor_key.MonitorValues) {
i.GatewaySuccessRateStr = fmt.Sprintf("%.2f%%", i.GatewaySuccessRate*100)
}
+//ProxyInfo 转发数量信息
type ProxyInfo struct {
ProxyRequestCount int64 `json:"proxyRequestCount"`
ProxySuccessCount int64 `json:"proxySuccessCount"`
@@ -57,28 +59,33 @@ func (i *ProxyInfo) read(values monitor_key.MonitorValues) {
i.ProxySuccessRateStr = fmt.Sprintf("%.2f%%", i.ProxySuccessRate*100)
}
+//BaseGatewayInfo 网关基本信息
type BaseGatewayInfo struct {
NodeCount int `json:"nodeCount"`
NodeStartCount int `json:"-"`
NodeStopCount int `json:"-"`
ProjectCount int `json:"projectCount"`
- ApiCount int `json:"apiCount"`
+ APICount int `json:"apiCount"`
StrategyCount int `json:"strategyCount"`
Version string `json:"version"`
ClusterCount int `json:"clusterCount"`
RedisCount int `json:"redisCount"`
}
+
+//SystemInfo 系统信息
type SystemInfo struct {
GatewayRequestInfo GatewayRequestInfo `json:"gatewayRequestInfo"`
ProxyInfo ProxyInfo `json:"proxyRequestInfo"`
BaseInfo BaseGatewayInfo `json:"baseInfo"`
}
+//Info info
type Info struct {
GatewayRequestInfo
ProxyInfo
}
+//Get get
func (i *Info) Get(key string) interface{} {
switch key {
case "gatewayRequestCount":
@@ -112,6 +119,8 @@ func (i *Info) Get(key string) interface{} {
}
return ""
}
+
+//Value value
func (i *Info) Value(key string) int64 {
switch key {
case "gatewayRequestCount":
@@ -151,17 +160,19 @@ func (i *Info) read(values monitor_key.MonitorValues) {
i.ProxyInfo.read(values)
}
+//APIInfo 接口信息
type APIInfo struct {
Info
- Id int `json:"apiID"`
+ ID int `json:"apiID"`
Name string `json:"apiName"`
URL string `json:"requestURL"`
}
+//Get get
func (i *APIInfo) Get(key string) interface{} {
switch key {
case "id":
- return i.Id
+ return i.ID
case "name":
return i.Name
case "url":
@@ -170,18 +181,20 @@ func (i *APIInfo) Get(key string) interface{} {
return i.Info.Get(key)
}
+//StrategyInfo 策略信息
type StrategyInfo struct {
Info
- Id string `json:"strategyID"`
+ ID string `json:"strategyID"`
Name string `json:"strategyName"`
Status string `json:"-"`
}
+//Get get
func (s *StrategyInfo) Get(key string) interface{} {
switch key {
case "id":
- return s.Id
+ return s.ID
case "name":
return s.Name
case "status":
@@ -191,30 +204,38 @@ func (s *StrategyInfo) Get(key string) interface{} {
}
+//StrategyInfoList 策略信息列表
type StrategyInfoList []*StrategyInfo
+//Value value
func (l StrategyInfoList) Value(i int, key string) int64 {
return l[i].Value(key)
}
+//Len len
func (l StrategyInfoList) Len() int {
return len(l)
}
+//Swap swap
func (l StrategyInfoList) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
+//APIInfoList 接口信息列表
type APIInfoList []*APIInfo
+//Value value
func (l APIInfoList) Value(i int, key string) int64 {
return l[i].Value(key)
}
+//Len len
func (l APIInfoList) Len() int {
return len(l)
}
+//Swap swap
func (l APIInfoList) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
diff --git a/console/module/monitor/gateway.go b/console/module/monitor/gateway.go
index 51aa7d2..7597421 100644
--- a/console/module/monitor/gateway.go
+++ b/console/module/monitor/gateway.go
@@ -1,17 +1,18 @@
package monitor
import (
- . "github.com/eolinker/goku-api-gateway/common/version"
+ v "github.com/eolinker/goku-api-gateway/common/version"
"github.com/eolinker/goku-api-gateway/server/cluster"
console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
dao_monitor "github.com/eolinker/goku-api-gateway/server/dao/console-mysql/dao-monitor"
)
-func GetGatewayMonitorSummaryByPeriod(clientId int, beginTime, endTime string, period int) (bool, *SystemInfo, error) {
+//GetGatewayMonitorSummaryByPeriod 获取网关监控概况
+func GetGatewayMonitorSummaryByPeriod(clientID int, beginTime, endTime string, period int) (bool, *SystemInfo, error) {
startHour, endHour := genHour(beginTime, endTime, period)
- values, e := dao_monitor.GetGateway(clientId, startHour, endHour)
+ values, e := dao_monitor.GetGateway(clientID, startHour, endHour)
if e != nil {
return false, nil, e
}
@@ -26,11 +27,11 @@ func GetGatewayMonitorSummaryByPeriod(clientId int, beginTime, endTime string, p
info.BaseInfo.NodeCount = nodeStartCount + nodeStopCount
info.BaseInfo.ProjectCount = projectCount
- info.BaseInfo.ApiCount = apiCount
+ info.BaseInfo.APICount = apiCount
info.BaseInfo.StrategyCount = strategyCount
activeRedisCount, redisErrorCount := console_mysql.GetRedisCount()
info.BaseInfo.RedisCount = activeRedisCount + redisErrorCount
- info.BaseInfo.Version = Version
+ info.BaseInfo.Version = v.Version
info.BaseInfo.ClusterCount = cluster.GetClusterCount()
//dao_monitor.GetGatewayMonitorSummaryByPeriod(beginTime, endTime, period)
return true, info, nil
diff --git a/console/module/node/node.go b/console/module/node/node.go
index 5ddd260..766818c 100644
--- a/console/module/node/node.go
+++ b/console/module/node/node.go
@@ -5,32 +5,32 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// 新增节点信息
-func AddNode(clusterId int, nodeName, nodeIP, nodePort, gatewayPath string, groupID int) (bool, map[string]interface{}, error) {
- return console_mysql.AddNode(clusterId, nodeName, nodeIP, nodePort, gatewayPath, groupID)
+//AddNode 新增节点信息
+func AddNode(clusterID int, nodeName, nodeIP, nodePort, gatewayPath string, groupID int) (bool, map[string]interface{}, error) {
+ return console_mysql.AddNode(clusterID, nodeName, nodeIP, nodePort, gatewayPath, groupID)
}
-// 修改节点
+//EditNode 修改节点
func EditNode(nodeName, nodeIP, nodePort, gatewayPath string, nodeID, groupID int) (bool, string, error) {
return console_mysql.EditNode(nodeName, nodeIP, nodePort, gatewayPath, nodeID, groupID)
}
-// 删除节点
+//DeleteNode 删除节点
func DeleteNode(nodeID int) (bool, string, error) {
return console_mysql.DeleteNode(nodeID)
}
-// 获取节点信息
+//GetNodeInfo 获取节点信息
func GetNodeInfo(nodeID int) (bool, *entity.Node, error) {
b, node, e := console_mysql.GetNodeInfo(nodeID)
ResetNodeStatus(node)
return b, node, e
}
-// 获取节点信息
-func GetNodeInfoByIpPort(ip string, port int) (bool, *entity.Node, error) {
- b, node, e := console_mysql.GetNodeByIpPort(ip, port)
+//GetNodeInfoByIPPort 获取节点信息
+func GetNodeInfoByIPPort(ip string, port int) (bool, *entity.Node, error) {
+ b, node, e := console_mysql.GetNodeByIPPort(ip, port)
ResetNodeStatus(node)
return b, node, e
}
@@ -42,12 +42,12 @@ func GetNodeList(clusterID, groupID int, keyword string) (bool, []*entity.Node,
return b, nodes, e
}
-// 节点IP查重
+//CheckIsExistRemoteAddr 节点IP查重
func CheckIsExistRemoteAddr(nodeID int, nodeIP, nodePort string) bool {
return console_mysql.CheckIsExistRemoteAddr(nodeID, nodeIP, nodePort)
}
-// 批量删除节点
+//BatchDeleteNode 批量删除节点
func BatchDeleteNode(nodeIDList string) (bool, string, error) {
flag, nodeIDList, err := console_mysql.GetAvaliableNodeListFromNodeList(nodeIDList, 0)
if !flag {
@@ -58,12 +58,12 @@ func BatchDeleteNode(nodeIDList string) (bool, string, error) {
return console_mysql.BatchDeleteNode(nodeIDList)
}
-// 批量修改节点分组
+//BatchEditNodeGroup 批量修改节点分组
func BatchEditNodeGroup(nodeIDList string, groupID int) (bool, string, error) {
return console_mysql.BatchEditNodeGroup(nodeIDList, groupID)
}
-// 获取节点IP列表
+//GetNodeIPList 获取节点IP列表
func GetNodeIPList() (bool, []map[string]interface{}, error) {
return console_mysql.GetNodeIPList()
}
diff --git a/console/module/node/nodeGroup.go b/console/module/node/nodeGroup.go
index f75b4ec..0dc79af 100644
--- a/console/module/node/nodeGroup.go
+++ b/console/module/node/nodeGroup.go
@@ -4,37 +4,37 @@ import (
"github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
-// 新建节点分组
-func AddNodeGroup(groupName string, clusterId int) (bool, interface{}, error) {
- return console_mysql.AddNodeGroup(groupName, clusterId)
+//AddNodeGroup 新建节点分组
+func AddNodeGroup(groupName string, clusterID int) (bool, interface{}, error) {
+ return consolemysql.AddNodeGroup(groupName, clusterID)
}
-// 修改节点分组信息
+//EditNodeGroup 修改节点分组信息
func EditNodeGroup(groupName string, groupID int) (bool, string, error) {
- return console_mysql.EditNodeGroup(groupName, groupID)
+ return consolemysql.EditNodeGroup(groupName, groupID)
}
-// 删除节点分组
+//DeleteNodeGroup 删除节点分组
func DeleteNodeGroup(groupID int) (bool, string, error) {
- return console_mysql.DeleteNodeGroup(groupID)
+ return consolemysql.DeleteNodeGroup(groupID)
}
-// 获取节点分组信息
+//GetNodeGroupInfo 获取节点分组信息
func GetNodeGroupInfo(groupID int) (bool, map[string]interface{}, error) {
- return console_mysql.GetNodeGroupInfo(groupID)
+ return consolemysql.GetNodeGroupInfo(groupID)
}
-// 获取节点分组列表
-func GetNodeGroupList(clusterId int) (bool, []map[string]interface{}, error) {
- return console_mysql.GetNodeGroupList(clusterId)
+//GetNodeGroupList 获取节点分组列表
+func GetNodeGroupList(clusterID int) (bool, []map[string]interface{}, error) {
+ return consolemysql.GetNodeGroupList(clusterID)
}
-// 检查节点分组是否存在
+//CheckNodeGroupIsExist 检查节点分组是否存在
func CheckNodeGroupIsExist(groupID int) (bool, error) {
- return console_mysql.CheckNodeGroupIsExist(groupID)
+ return consolemysql.CheckNodeGroupIsExist(groupID)
}
-// 获取分组内启动节点数量
+//GetRunningNodeCount 获取分组内启动节点数量
func GetRunningNodeCount(groupID int) (bool, interface{}, error) {
- return console_mysql.GetRunningNodeCount(groupID)
+ return consolemysql.GetRunningNodeCount(groupID)
}
diff --git a/console/module/node/status.go b/console/module/node/status.go
index 5277e40..da44095 100644
--- a/console/module/node/status.go
+++ b/console/module/node/status.go
@@ -7,6 +7,7 @@ import (
"time"
)
+//EXPIRE 过期时间
const EXPIRE = time.Second * 10
var (
@@ -45,16 +46,19 @@ func (m *_StatusManager) get(id string) (time.Time, bool) {
return t, b
}
+//Refresh 刷新
func Refresh(ip string, port string) {
id := fmt.Sprintf("%s:%d", ip, port)
manager.refresh(id)
}
+//NodeStop 停止节点
func NodeStop(ip, port string) {
id := fmt.Sprintf("%s:%d", ip, port)
manager.stop(id)
}
+//IsLive 是否正常
func IsLive(ip string, port string) bool {
id := fmt.Sprintf("%s:%d", ip, port)
t, has := manager.get(id)
@@ -67,6 +71,8 @@ func IsLive(ip string, port string) bool {
}
return true
}
+
+//ResetNodeStatus 重置节点状态
func ResetNodeStatus(nodes ...*entity.Node) {
for _, node := range nodes {
diff --git a/console/module/plugin/plugin.go b/console/module/plugin/plugin.go
index 3228d03..df2d85a 100644
--- a/console/module/plugin/plugin.go
+++ b/console/module/plugin/plugin.go
@@ -2,108 +2,88 @@ package plugin
import (
"github.com/eolinker/goku-api-gateway/server/dao"
- console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
+ consolemysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// 获取插件配置信息
+//GetPluginInfo 获取插件配置信息
func GetPluginInfo(pluginName string) (bool, *entity.Plugin, error) {
- return console_mysql.GetPluginInfo(pluginName)
+ return consolemysql.GetPluginInfo(pluginName)
}
-// 获取插件列表
+//GetPluginList 获取插件列表
func GetPluginList(keyword string, condition int) (bool, []*entity.Plugin, error) {
- return console_mysql.GetPluginList(keyword, condition)
+ return consolemysql.GetPluginList(keyword, condition)
}
-// 新增插件信息
+//AddPlugin 新增插件信息
func AddPlugin(pluginName, pluginConfig, pluginDesc, version string, pluginPriority, isStop, pluginType int) (bool, string, error) {
- return console_mysql.AddPlugin(pluginName, pluginConfig, pluginDesc, version, pluginPriority, isStop, pluginType)
+ return consolemysql.AddPlugin(pluginName, pluginConfig, pluginDesc, version, pluginPriority, isStop, pluginType)
}
-// 修改插件信息
+//EditPlugin 修改插件信息
func EditPlugin(pluginName, pluginConfig, pluginDesc, version string, pluginPriority, isStop, pluginType int) (bool, string, error) {
- return console_mysql.EditPlugin(pluginName, pluginConfig, pluginDesc, version, pluginPriority, isStop, pluginType)
+ return consolemysql.EditPlugin(pluginName, pluginConfig, pluginDesc, version, pluginPriority, isStop, pluginType)
}
-// 删除插件信息
+//DeletePlugin 删除插件信息
func DeletePlugin(pluginName string) (bool, string, error) {
- return console_mysql.DeletePlugin(pluginName)
+ return consolemysql.DeletePlugin(pluginName)
}
-// 判断插件ID是否存在
+//CheckIndexIsExist 判断插件ID是否存在
func CheckIndexIsExist(pluginName string, pluginPriority int) (bool, error) {
- return console_mysql.CheckIndexIsExist(pluginName, pluginPriority)
+ return consolemysql.CheckIndexIsExist(pluginName, pluginPriority)
}
-// 获取插件配置及插件信息
+//GetPluginConfig 获取插件配置及插件信息
func GetPluginConfig(pluginName string) (bool, string, error) {
- return console_mysql.GetPluginConfig(pluginName)
+ return consolemysql.GetPluginConfig(pluginName)
}
-// 检查插件名称是否存在
+//CheckNameIsExist 检查插件名称是否存在
func CheckNameIsExist(pluginName string) (bool, error) {
- return console_mysql.CheckNameIsExist(pluginName)
+ return consolemysql.CheckNameIsExist(pluginName)
}
-// 修改插件开启状态
+//EditPluginStatus 修改插件开启状态
func EditPluginStatus(pluginName string, pluginStatus int) (bool, error) {
tableName := "goku_plugin"
- flag, err := console_mysql.EditPluginStatus(pluginName, pluginStatus)
+ flag, err := consolemysql.EditPluginStatus(pluginName, pluginStatus)
if flag {
dao.UpdateTable(tableName)
- console_mysql.UpdatePluginTagByPluginName(pluginName)
+ consolemysql.UpdatePluginTagByPluginName(pluginName)
}
return flag, err
}
-// 获取不同类型的插件列表
+//GetPluginListByPluginType 获取不同类型的插件列表
func GetPluginListByPluginType(pluginType int) (bool, []map[string]interface{}, error) {
- return console_mysql.GetPluginListByPluginType(pluginType)
+ return consolemysql.GetPluginListByPluginType(pluginType)
}
-// 批量关闭插件
+//BatchStopPlugin 批量关闭插件
func BatchStopPlugin(pluginNameList string) (bool, string, error) {
- //if strings.Contains(pluginNameList, "goku-rate_limiting") {
- // updateFlag, errInfo := console_mysql.DeleteRateInfoInRedis("")
- // if !updateFlag {
- // utils.SystemLog(errInfo)
- // }
- //} else if strings.Contains(pluginNameList, "goku-replay_attack_defender") {
- // updateFlag, errInfo := console_mysql.DeleteReplayAttackTokenInRedis("")
- // if !updateFlag {
- // utils.SystemLog(errInfo)
- // }
- //} else if strings.Contains(pluginNameList, "goku-oauth2_auth") {
- // updateFlag, errInfo := console_mysql.DeleteOauth2InfoInRedis("", "")
- // if !updateFlag {
- // utils.SystemLog(errInfo)
- // }
- //} else if strings.Contains(pluginNameList, "goku-proxy_caching") {
- // console_mysql.ClearRedisProxyCache("", 0)
- //} else if strings.Contains(pluginNameList, "goku-circuit_breaker") {
- // console_mysql.ClearRedisCircuitBreaker("", 0)
- //}
tableName := "goku_plugin"
- flag, result, err := console_mysql.BatchStopPlugin(pluginNameList)
+ flag, result, err := consolemysql.BatchStopPlugin(pluginNameList)
if flag {
dao.UpdateTable(tableName)
}
return flag, result, err
}
-// 批量关闭插件
+//BatchStartPlugin 批量关闭插件
func BatchStartPlugin(pluginNameList string) (bool, string, error) {
tableName := "goku_plugin"
- flag, result, err := console_mysql.BatchStartPlugin(pluginNameList)
+ flag, result, err := consolemysql.BatchStartPlugin(pluginNameList)
if flag {
dao.UpdateTable(tableName)
- console_mysql.UpdatePluginTagByPluginName(pluginNameList)
+ consolemysql.UpdatePluginTagByPluginName(pluginNameList)
}
return flag, result, err
}
-// 更新插件检测状态
+//EditPluginCheckStatus 更新插件检测状态
func EditPluginCheckStatus(pluginName string, isCheck int) (bool, string, error) {
- return console_mysql.EditPluginCheckStatus(pluginName, isCheck)
+ return consolemysql.EditPluginCheckStatus(pluginName, isCheck)
}
diff --git a/console/module/project/project.go b/console/module/project/project.go
index ca2ade2..556d625 100644
--- a/console/module/project/project.go
+++ b/console/module/project/project.go
@@ -6,17 +6,17 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// 新建项目
+//AddProject 新建项目
func AddProject(projectName string) (bool, interface{}, error) {
return console_mysql.AddProject(projectName)
}
-// 修改项目信息
+//EditProject 修改项目信息
func EditProject(projectName string, projectID int) (bool, string, error) {
return console_mysql.EditProject(projectName, projectID)
}
-// 修改项目信息
+//DeleteProject 修改项目信息
func DeleteProject(projectID int) (bool, string, error) {
flag, result, err := console_mysql.DeleteProject(projectID)
if flag {
@@ -26,7 +26,7 @@ func DeleteProject(projectID int) (bool, string, error) {
return flag, result, err
}
-// 批量删除项目
+//BatchDeleteProject 批量删除项目
func BatchDeleteProject(projectIDList string) (bool, string, error) {
flag, result, err := console_mysql.BatchDeleteProject(projectIDList)
if flag {
@@ -36,22 +36,22 @@ func BatchDeleteProject(projectIDList string) (bool, string, error) {
return flag, result, err
}
-// 获取项目信息
+//GetProjectInfo 获取项目信息
func GetProjectInfo(projectID int) (bool, entity.Project, error) {
return console_mysql.GetProjectInfo(projectID)
}
-// 获取项目列表
+//GetProjectList 获取项目列表
func GetProjectList(keyword string) (bool, []*entity.Project, error) {
return console_mysql.GetProjectList(keyword)
}
-// 检查项目是否存在
+//CheckProjectIsExist 检查项目是否存在
func CheckProjectIsExist(projectID int) (bool, error) {
return console_mysql.CheckProjectIsExist(projectID)
}
-// 获取项目列表中没有被策略组绑定的接口
-func GetApiListFromProjectNotInStrategy() (bool, []map[string]interface{}, error) {
- return console_mysql.GetApiListFromProjectNotInStrategy()
+//GetAPIListFromProjectNotInStrategy 获取项目列表中没有被策略组绑定的接口
+func GetAPIListFromProjectNotInStrategy() (bool, []map[string]interface{}, error) {
+ return console_mysql.GetAPIListFromProjectNotInStrategy()
}
diff --git a/console/module/script/script.go b/console/module/script/script.go
index 909394f..c2a1f3e 100644
--- a/console/module/script/script.go
+++ b/console/module/script/script.go
@@ -2,20 +2,21 @@ package script
import (
"github.com/eolinker/goku-api-gateway/server/dao"
- console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
+ consolemysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
-// 新建项目
-func RefreshApiInfo() bool {
- //return console_mysql.RefreshApiInfo()
+//RefreshAPIInfo 刷新接口信息
+func RefreshAPIInfo() bool {
+ //return consolemysql.RefreshAPIInfo()
return true
}
-// 新建项目
+//RefreshGatewayAlertConfig 刷新网关告警配置
func RefreshGatewayAlertConfig() bool {
- return console_mysql.RefreshGatewayAlertConfig()
+ return consolemysql.RefreshGatewayAlertConfig()
}
+//UpdateTables 更新表
func UpdateTables(names []string) {
for _, name := range names {
dao.UpdateTable(name)
diff --git a/console/module/service/check.go b/console/module/service/check.go
index f4a3599..1ba184e 100644
--- a/console/module/service/check.go
+++ b/console/module/service/check.go
@@ -22,6 +22,8 @@ func init() {
func f(r rune) bool {
return !nameLetters[r]
}
+
+//ValidateName 判断名称是否合法
func ValidateName(name string) bool {
if name == "" {
return false
diff --git a/console/module/service/module.go b/console/module/service/module.go
index e06ac21..31e0bde 100644
--- a/console/module/service/module.go
+++ b/console/module/service/module.go
@@ -10,6 +10,7 @@ import (
const _TableName = "goku_service_config"
+//Add add
func Add(param *AddParam) error {
err := dao_service.Add(param.Name, param.Driver, param.Desc, param.Config, param.ClusterConfig, false, param.HealthCheck, param.HealthCheckPath, param.HealthCheckCode, param.HealthCheckPeriod, param.HealthCheckTimeOut)
@@ -20,6 +21,7 @@ func Add(param *AddParam) error {
return err
}
+//Save save
func Save(param *AddParam) error {
v, e := dao_service.Get(param.Name)
@@ -37,6 +39,8 @@ func Save(param *AddParam) error {
}
return err
}
+
+//Get get
func Get(name string) (*Info, error) {
v, err := dao_service.Get(name)
if err != nil {
@@ -54,6 +58,7 @@ func Get(name string) (*Info, error) {
}, nil
}
+//Delete delete
func Delete(names []string) error {
for _, n := range names {
@@ -65,6 +70,7 @@ func Delete(names []string) error {
return dao_service.Delete(names)
}
+//SetDefaut 设置默认值
func SetDefaut(name string) error {
return dao_service.SetDefault(name)
}
@@ -91,6 +97,8 @@ func tran(v *entity.Service) *Service {
}
return s
}
+
+//List 获取列表
func List(keyword string) ([]*Service, error) {
vs, e := dao_service.List(keyword)
if e != nil {
@@ -106,6 +114,7 @@ func List(keyword string) ([]*Service, error) {
return list, nil
}
+//SimpleList 获取简易列表
func SimpleList() ([]*Simple, string, error) {
vs, e := dao_service.List("")
if e != nil {
diff --git a/console/module/service/service.go b/console/module/service/service.go
index ad84c62..2393590 100644
--- a/console/module/service/service.go
+++ b/console/module/service/service.go
@@ -2,6 +2,7 @@ package service
import "encoding/json"
+//Simple simple
type Simple struct {
Name string `json:"name"`
Driver string `json:"driver"`
@@ -9,6 +10,7 @@ type Simple struct {
Type string `json:"type"`
}
+//Service service
type Service struct {
Simple
@@ -19,6 +21,7 @@ type Service struct {
CreateTime string `json:"createTime"`
}
+//Info info
type Info struct {
*Service
Config string `json:"config"`
@@ -30,10 +33,12 @@ type Info struct {
HealthCheckTimeOut int `json:"healthCheckTimeOut"`
}
+//Decode 解码
func (i *Info) Decode() {
json.Unmarshal([]byte(i.ClusterConfig), &i.ClusterConfigObj)
}
+//AddParam add param
type AddParam struct {
Name string `opt:"name,require"`
Driver string `opt:"driver" default:"static"`
diff --git a/console/module/strategy/strategy.go b/console/module/strategy/strategy.go
index 8215611..1af200b 100644
--- a/console/module/strategy/strategy.go
+++ b/console/module/strategy/strategy.go
@@ -8,22 +8,21 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// 新增策略组
+//AddStrategy 新增策略组
func AddStrategy(strategyName string, groupID int) (bool, string, error) {
flag := console_mysql.CheckIsOpenGroup(groupID)
if flag {
return false, "[ERROR]The group is an open group", errors.New("[ERROR]The group is an open group")
- } else {
- flag, result, err := console_mysql.AddStrategy(strategyName, groupID)
- if flag {
- tableName := "goku_gateway_strategy"
- dao.UpdateTable(tableName)
- }
- return flag, result, err
}
+ flag, result, err := console_mysql.AddStrategy(strategyName, groupID)
+ if flag {
+ tableName := "goku_gateway_strategy"
+ dao.UpdateTable(tableName)
+ }
+ return flag, result, err
}
-// 修改策略组信息
+//EditStrategy 修改策略组信息
func EditStrategy(strategyID, strategyName string, groupID int) (bool, string, error) {
return console_mysql.EditStrategy(strategyID, strategyName, groupID)
}
@@ -33,14 +32,13 @@ func DeleteStrategy(strategyID string) (bool, string, error) {
flag := console_mysql.CheckIsOpenStrategy(strategyID)
if flag {
return false, "[ERROR]The strategy is an open strategy", errors.New("[ERROR]The strategy is an open strategy")
- } else {
- tableName := "goku_gateway_strategy"
- flag, result, err := console_mysql.DeleteStrategy(strategyID)
- if flag {
- dao.UpdateTable(tableName)
- }
- return flag, result, err
}
+ tableName := "goku_gateway_strategy"
+ flag, result, err := console_mysql.DeleteStrategy(strategyID)
+ if flag {
+ dao.UpdateTable(tableName)
+ }
+ return flag, result, err
}
// GetOpenStrategy 获取策略组列表
@@ -78,18 +76,19 @@ func BatchDeleteStrategy(strategyIDList string) (bool, string, error) {
return flag, result, err
}
+//CheckIsOpenStrategy 是否是开放策略
func CheckIsOpenStrategy(strategyID string) bool {
return console_mysql.CheckIsOpenStrategy(strategyID)
}
-// 更新策略启用状态
+//BatchUpdateStrategyEnableStatus 更新策略启用状态
func BatchUpdateStrategyEnableStatus(strategyIDList string, enableStatus int) (bool, string, error) {
tableName := "goku_gateway_strategy"
flag, result, err := console_mysql.BatchUpdateStrategyEnableStatus(strategyIDList, enableStatus)
if flag {
dao.UpdateTable(tableName)
console_mysql.BatchUpdateStrategyPluginUpdateTag(strategyIDList)
- console_mysql.BatchUpdateApiPluginUpdateTag(strategyIDList)
+ console_mysql.BatchUpdateAPIPluginUpdateTag(strategyIDList)
}
return flag, result, err
}
diff --git a/console/module/strategy/strategyGroup.go b/console/module/strategy/strategyGroup.go
index 44100f7..94858f9 100644
--- a/console/module/strategy/strategyGroup.go
+++ b/console/module/strategy/strategyGroup.go
@@ -7,12 +7,12 @@ import (
console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
-// 新建策略组分组
+//AddStrategyGroup 新建策略组分组
func AddStrategyGroup(groupName string) (bool, interface{}, error) {
return console_mysql.AddStrategyGroup(groupName)
}
-// 修改策略组分组
+//EditStrategyGroup 修改策略组分组
func EditStrategyGroup(groupName string, groupID int) (bool, string, error) {
return console_mysql.EditStrategyGroup(groupName, groupID)
}
@@ -22,24 +22,24 @@ func DeleteStrategyGroup(groupID int) (bool, string, error) {
flag := console_mysql.CheckIsOpenGroup(groupID)
if flag {
return false, "[ERROR]The group is an open group", errors.New("[ERROR]The group is an open group")
- } else {
- flag, result, err := console_mysql.DeleteStrategyGroup(groupID)
- if flag {
- dao.UpdateTable("goku_gateway_strategy")
- dao.UpdateTable("goku_gateway_api")
- dao.UpdateTable("goku_conn_strategy_api")
- dao.UpdateTable("goku_conn_plugin_strategy")
- dao.UpdateTable("goku_conn_plugin_api")
- }
- return flag, result, err
}
+ flag, result, err := console_mysql.DeleteStrategyGroup(groupID)
+ if flag {
+ dao.UpdateTable("goku_gateway_strategy")
+ dao.UpdateTable("goku_gateway_api")
+ dao.UpdateTable("goku_conn_strategy_api")
+ dao.UpdateTable("goku_conn_plugin_strategy")
+ dao.UpdateTable("goku_conn_plugin_api")
+ }
+ return flag, result, err
}
-// 获取策略组分组列表
+//GetStrategyGroupList 获取策略组分组列表
func GetStrategyGroupList() (bool, []map[string]interface{}, error) {
return console_mysql.GetStrategyGroupList()
}
+//CheckIsOpenGroup 判断是否是开放分组
func CheckIsOpenGroup(groupID int) bool {
return console_mysql.CheckIsOpenGroup(groupID)
}
diff --git a/console/module/strategy/strategyPlugin.go b/console/module/strategy/strategyPlugin.go
index 903a704..a49c348 100644
--- a/console/module/strategy/strategyPlugin.go
+++ b/console/module/strategy/strategyPlugin.go
@@ -7,7 +7,7 @@ import (
console_mysql "github.com/eolinker/goku-api-gateway/server/dao/console-mysql"
)
-// 新增策略组插件
+//AddPluginToStrategy 新增策略组插件
func AddPluginToStrategy(pluginName, config, strategyID string) (bool, interface{}, error) {
tableName := "goku_conn_plugin_strategy"
flag, result, err := console_mysql.AddPluginToStrategy(pluginName, config, strategyID)
@@ -18,7 +18,7 @@ func AddPluginToStrategy(pluginName, config, strategyID string) (bool, interface
return flag, result, err
}
-// 新增策略组插件配置
+//EditStrategyPluginConfig 新增策略组插件配置
func EditStrategyPluginConfig(pluginName, config, strategyID string) (bool, string, error) {
flag, result, err := console_mysql.EditStrategyPluginConfig(pluginName, config, strategyID)
tableName := "goku_conn_plugin_strategy"
@@ -29,7 +29,7 @@ func EditStrategyPluginConfig(pluginName, config, strategyID string) (bool, stri
return flag, result, err
}
-// 批量修改策略组插件状态
+//BatchEditStrategyPluginStatus 批量修改策略组插件状态
func BatchEditStrategyPluginStatus(connIDList, strategyID string, pluginStatus int) (bool, string, error) {
plugins := []string{}
flag, _ := console_mysql.CheckStrategyPluginIsExistByConnIDList(connIDList, "goku-rate_limiting")
@@ -50,7 +50,7 @@ func BatchEditStrategyPluginStatus(connIDList, strategyID string, pluginStatus i
return flag, result, err
}
-// 批量删除策略组插件
+//BatchDeleteStrategyPlugin 批量删除策略组插件
func BatchDeleteStrategyPlugin(connIDList, strategyID string) (bool, string, error) {
tableName := "goku_conn_plugin_strategy"
flag, result, err := console_mysql.BatchDeleteStrategyPlugin(connIDList, strategyID)
@@ -65,22 +65,22 @@ func GetStrategyPluginList(strategyID, keyword string, condition int) (bool, []m
return console_mysql.GetStrategyPluginList(strategyID, keyword, condition)
}
-// 通过策略组ID获取配置信息
+//GetStrategyPluginConfig 通过策略组ID获取配置信息
func GetStrategyPluginConfig(strategyID, pluginName string) (bool, string, error) {
return console_mysql.GetStrategyPluginConfig(strategyID, pluginName)
}
-// 检查策略组是否绑定插件
+//CheckPluginIsExistInStrategy 检查策略组是否绑定插件
func CheckPluginIsExistInStrategy(strategyID, pluginName string) (bool, error) {
return console_mysql.CheckPluginIsExistInStrategy(strategyID, pluginName)
}
-// 检查策略组插件是否开启
+//GetStrategyPluginStatus 检查策略组插件是否开启
func GetStrategyPluginStatus(strategyID, pluginName string) (bool, error) {
return console_mysql.GetStrategyPluginStatus(strategyID, pluginName)
}
-// 获取Connid
+//GetConnIDFromStrategyPlugin 获取Connid
func GetConnIDFromStrategyPlugin(pluginName, strategyID string) (bool, int, error) {
return console_mysql.GetConnIDFromStrategyPlugin(pluginName, strategyID)
}
diff --git a/console/redis_config.go b/console/redis_config.go
index 3d6618a..3d0df55 100644
--- a/console/redis_config.go
+++ b/console/redis_config.go
@@ -5,24 +5,30 @@ import (
"strings"
)
+//ClusterRedisConfig 集群redis配置
type ClusterRedisConfig entity.CLusterRedis
+//GetMode 获取redis模式
func (c ClusterRedisConfig) GetMode() string {
return c.Mode
}
+//GetAddrs 获取redis地址
func (c ClusterRedisConfig) GetAddrs() []string {
return strings.Split(c.Addrs, ",")
}
+//GetMasters getMasters
func (c ClusterRedisConfig) GetMasters() []string {
return strings.Split(c.Masters, ",")
}
+//GetDbIndex 获取redis数据库序号
func (c ClusterRedisConfig) GetDbIndex() int {
return c.DbIndex
}
+//GetPassword 获取redis密码
func (c ClusterRedisConfig) GetPassword() string {
return c.Password
}
diff --git a/console/router.go b/console/router.go
index 070b636..0af3dc4 100644
--- a/console/router.go
+++ b/console/router.go
@@ -21,6 +21,7 @@ import (
"github.com/eolinker/goku-api-gateway/console/controller/strategy"
)
+//Router 路由
func Router() {
// 游客
@@ -51,38 +52,38 @@ func Router() {
http.HandleFunc("/project/delete", project.DeleteProject)
http.HandleFunc("/project/getInfo", project.GetProjectInfo)
http.HandleFunc("/project/getList", project.GetProjectList)
- http.HandleFunc("/project/strategy/getList", project.GetApiListFromProjectNotInStrategy)
+ http.HandleFunc("/project/strategy/getList", project.GetAPIListFromProjectNotInStrategy)
http.HandleFunc("/project/batchDelete", project.BatchDeleteProject)
// 接口分组
- http.HandleFunc("/apis/group/add", api.AddApiGroup)
- http.HandleFunc("/apis/group/edit", api.EditApiGroup)
- http.HandleFunc("/apis/group/delete", api.DeleteApiGroup)
- http.HandleFunc("/apis/group/getList", api.GetApiGroupList)
- http.HandleFunc("/apis/group/update", api.UpdateApiGroupScript)
+ http.HandleFunc("/apis/group/add", api.AddAPIGroup)
+ http.HandleFunc("/apis/group/edit", api.EditAPIGroup)
+ http.HandleFunc("/apis/group/delete", api.DeleteAPIGroup)
+ http.HandleFunc("/apis/group/getList", api.GetAPIGroupList)
+ http.HandleFunc("/apis/group/update", api.UpdateAPIGroupScript)
// API
- http.HandleFunc("/apis/add", api.AddApi)
- http.HandleFunc("/apis/edit", api.EditApi)
- http.HandleFunc("/apis/copy", api.CopyApi)
- http.HandleFunc("/apis/getInfo", api.GetApiInfo)
- http.HandleFunc("/apis/getList", api.GetApiList)
- http.HandleFunc("/apis/batchEditGroup", api.BatchEditApiGroup)
- http.HandleFunc("/apis/batchDelete", api.BatchDeleteApi)
- http.HandleFunc("/apis/batchEditBalance", api.BatchSetBalanceApi)
+ http.HandleFunc("/apis/add", api.AddAPI)
+ http.HandleFunc("/apis/edit", api.EditAPI)
+ http.HandleFunc("/apis/copy", api.CopyAPI)
+ http.HandleFunc("/apis/getInfo", api.GetAPIInfo)
+ http.HandleFunc("/apis/getList", api.GetAPIList)
+ http.HandleFunc("/apis/batchEditGroup", api.BatchEditAPIGroup)
+ http.HandleFunc("/apis/batchDelete", api.BatchDeleteAPI)
+ http.HandleFunc("/apis/batchEditBalance", api.BatchSetBalanceAPI)
- http.HandleFunc("/apis/manager/getList", api.GetApiManagerList)
+ http.HandleFunc("/apis/manager/getList", api.GetAPIManagerList)
// API绑定插件
- http.HandleFunc("/plugin/api/addPluginToApi", api.AddPluginToApi)
- http.HandleFunc("/plugin/api/edit", api.EditApiPluginConfig)
- http.HandleFunc("/plugin/api/getInfo", api.GetApiPluginConfig)
- http.HandleFunc("/plugin/api/getList", api.GetApiPluginList)
- http.HandleFunc("/plugin/api/getListByStrategy", api.GetAllApiPluginInStrategy)
- http.HandleFunc("/plugin/api/batchStart", api.BatchStartApiPlugin)
- http.HandleFunc("/plugin/api/batchStop", api.BatchStopApiPlugin)
- http.HandleFunc("/plugin/api/batchDelete", api.BatchDeleteApiPlugin)
- http.HandleFunc("/plugin/api/notAssign/getList", api.GetApiPluginListWithNotAssignApiList)
+ http.HandleFunc("/plugin/api/addPluginToAPI", api.AddPluginToAPI)
+ http.HandleFunc("/plugin/api/edit", api.EditAPIPluginConfig)
+ http.HandleFunc("/plugin/api/getInfo", api.GetAPIPluginConfig)
+ http.HandleFunc("/plugin/api/getList", api.GetAPIPluginList)
+ http.HandleFunc("/plugin/api/getListByStrategy", api.GetAllAPIPluginInStrategy)
+ http.HandleFunc("/plugin/api/batchStart", api.BatchStartAPIPlugin)
+ http.HandleFunc("/plugin/api/batchStop", api.BatchStopAPIPlugin)
+ http.HandleFunc("/plugin/api/batchDelete", api.BatchDeleteAPIPlugin)
+ http.HandleFunc("/plugin/api/notAssign/getList", api.GetAPIPluginListWithNotAssignAPIList)
// 策略绑定插件
http.HandleFunc("/plugin/strategy/addPluginToStrategy", strategy.AddPluginToStrategy)
@@ -136,12 +137,12 @@ func Router() {
http.HandleFunc("/strategy/group/getList", strategy.GetStrategyGroupList)
// 接口策略组
- http.HandleFunc("/strategy/api/add", strategy.AddApiToStrategy)
- http.HandleFunc("/strategy/api/target", strategy.ResetApiTargetOfStrategy)
- http.HandleFunc("/strategy/api/batchEditTarget", strategy.BatchResetApiTargetOfStrategy)
- http.HandleFunc("/strategy/api/getList", strategy.GetApiListFromStrategy)
- http.HandleFunc("/strategy/api/getNotInList", strategy.GetApiListNotInStrategy)
- http.HandleFunc("/strategy/api/batchDelete", strategy.BatchDeleteApiInStrategy)
+ http.HandleFunc("/strategy/api/add", strategy.AddAPIToStrategy)
+ http.HandleFunc("/strategy/api/target", strategy.ResetAPITargetOfStrategy)
+ http.HandleFunc("/strategy/api/batchEditTarget", strategy.BatchResetAPITargetOfStrategy)
+ http.HandleFunc("/strategy/api/getList", strategy.GetAPIListFromStrategy)
+ http.HandleFunc("/strategy/api/getNotInList", strategy.GetAPIListNotInStrategy)
+ http.HandleFunc("/strategy/api/batchDelete", strategy.BatchDeleteAPIInStrategy)
http.HandleFunc("/strategy/api/plugin/getList", api.GetAPIPluginInStrategyByAPIID)
http.HandleFunc("/strategy/balance/getList", strategy.GetBalanceListInStrategy)
@@ -182,8 +183,8 @@ func Router() {
http.HandleFunc("/auth/editInfo", auth.EditAuthInfo)
// 导入
- http.HandleFunc("/import/ams/api", api.ImportApiFromAms)
- http.HandleFunc("/import/ams/group", api.ImportApiGroupFromAms)
+ http.HandleFunc("/import/ams/api", api.ImportAPIFromAms)
+ http.HandleFunc("/import/ams/group", api.ImportAPIGroupFromAms)
http.HandleFunc("/import/ams/project", api.ImportProjectFromAms)
// 集群
@@ -192,7 +193,7 @@ func Router() {
http.HandleFunc("/cluster/simpleList", cluster.GetClusterList)
// 脚本
- http.HandleFunc("/scrpit/refreshApiInfo", script.RefreshApiInfo)
+ http.HandleFunc("/scrpit/refreshAPIInfo", script.RefreshAPIInfo)
http.HandleFunc("/scrpit/refreshGatewayAlertConfig", script.RefreshGatewayAlertConfig)
// 配置
http.Handle("/config/log/", config_log.Handle("/config/log/"))
diff --git a/console/server.go b/console/server.go
index 8621bff..1f5892a 100644
--- a/console/server.go
+++ b/console/server.go
@@ -5,8 +5,6 @@ import (
log "github.com/eolinker/goku-api-gateway/goku-log"
- _ "net/http/pprof"
-
"github.com/eolinker/goku-api-gateway/console/controller/api"
"github.com/eolinker/goku-api-gateway/console/controller/script"
"github.com/eolinker/goku-api-gateway/console/controller/strategy"
@@ -18,11 +16,12 @@ import (
"github.com/eolinker/goku-api-gateway/console/module/account"
)
+//Server 服务
func Server() {
//go monitor.MonitorNode()
monitor_read.InitMonitorRead(cluster2.GetList())
script.UpdateTables()
- api.UpdateAllApiPluginUpdateTag()
+ api.UpdateAllAPIPluginUpdateTag()
strategy.UpdateAllStrategyPluginUpdateTag()
bind, has := conf.Get("admin_bind")
@@ -66,7 +65,7 @@ func Server() {
}
-// 用户注册
+// Register 用户注册
func Register(loginCall, loginPassword string) bool {
return account.Register(loginCall, loginPassword)
}
diff --git a/goku-log/debug.go b/goku-log/debug.go
index 58ee4fc..cf04891 100644
--- a/goku-log/debug.go
+++ b/goku-log/debug.go
@@ -1,4 +1,4 @@
-package goku_log
+package gokulog
import (
"fmt"
@@ -6,6 +6,7 @@ import (
"os"
)
+// StartDebug 启用debug钩子
func StartDebug() {
logger.AddHook(new(debugHook))
diff --git a/goku-log/exported.go b/goku-log/exported.go
index 6e889b1..89cda03 100644
--- a/goku-log/exported.go
+++ b/goku-log/exported.go
@@ -1,4 +1,4 @@
-package goku_log
+package gokulog
import (
"fmt"
@@ -8,26 +8,39 @@ import (
)
const (
+ //PanicLevel panic
PanicLevel = logrus.PanicLevel
+ //FatalLevel fatal
FatalLevel = logrus.FatalLevel
+ //ErrorLevel error
ErrorLevel = logrus.ErrorLevel
+ //WarnLevel warn
WarnLevel = logrus.WarnLevel
+ //InfoLevel info
InfoLevel = logrus.InfoLevel
+ //DebugLevel debug
DebugLevel = logrus.DebugLevel
+ //TraceLevel trace
TraceLevel = logrus.TraceLevel
)
var (
- writer *FileWriterByPeriod = nil
+ writer *FileWriterByPeriod
logger = logrus.New()
logEnable = true
)
+//Level level
type Level = logrus.Level
+
+//Fields fields
type Fields = logrus.Fields
+
+//Entry entry
type Entry = logrus.Entry
+//ParseLevel 转换层级
func ParseLevel(lvl string) (Level, error) {
return logrus.ParseLevel(lvl)
}
@@ -45,14 +58,20 @@ func init() {
Close()
})
}
+
+//GetLogger 获取日志对象
func GetLogger() *logrus.Logger {
return logger
}
+
+//SetLevel 设置日志层级
func SetLevel(level Level) {
logger.SetLevel(level)
}
+
+//SetOutPut 输出设置
func SetOutPut(enable bool, dir, file string, period LogPeriod, expire int) {
logEnable = enable
logger.SetOutput(writer)
@@ -64,9 +83,12 @@ func SetOutPut(enable bool, dir, file string, period LogPeriod, expire int) {
}
}
+//Close 关闭流
func Close() {
writer.Close()
}
+
+//WithFields 设置日志需要的字段名称
func WithFields(fields Fields) *Entry {
return logger.WithFields(fields)
@@ -235,7 +257,7 @@ func Debugln(args ...interface{}) {
logger.Debugln(args...)
}
-// 无视lever输出一段trace 信息
+// Print 无视lever输出一段trace 信息
func Print(args ...interface{}) {
s, e := encode(TraceLevel, args...)
diff --git a/goku-log/exported_test.go b/goku-log/exported_test.go
index f4808fb..e4ab6ee 100644
--- a/goku-log/exported_test.go
+++ b/goku-log/exported_test.go
@@ -1 +1 @@
-package goku_log
+package gokulog
diff --git a/goku-log/formatter.go b/goku-log/formatter.go
index 19b3b5e..e38a209 100644
--- a/goku-log/formatter.go
+++ b/goku-log/formatter.go
@@ -1,4 +1,4 @@
-package goku_log
+package gokulog
import (
"bytes"
@@ -13,11 +13,13 @@ const (
defaultTimestampFormat = time.RFC3339
)
+//LineFormatter 格式化
type LineFormatter struct {
TimestampFormat string
CallerPrettyfier func(*runtime.Frame) (function string, file string)
}
+//Format 格式化
func (f *LineFormatter) Format(entry *logrus.Entry) ([]byte, error) {
data := make(Fields)
for k, v := range entry.Data {
diff --git a/goku-log/period.go b/goku-log/period.go
index 702baba..6d82224 100644
--- a/goku-log/period.go
+++ b/goku-log/period.go
@@ -1,16 +1,20 @@
-package goku_log
+package gokulog
import (
"fmt"
"strings"
)
+//LogPeriod 日志周期对象
type LogPeriod interface {
String() string
FormatLayout() string
}
+
+//LogPeriodType 日志周期类型
type LogPeriodType int
+//ParsePeriod 解析周期
func ParsePeriod(v string) (LogPeriod, error) {
switch strings.ToLower(v) {
case "month":
@@ -37,11 +41,15 @@ func (period LogPeriodType) String() string {
}
const (
+ //PeriodMonth 月
PeriodMonth LogPeriodType = iota
+ //PeriodDay 天
PeriodDay
+ //PeriodHour 时
PeriodHour
)
+//FormatLayout 设置时间格式
func (period LogPeriodType) FormatLayout() string {
switch period {
case PeriodHour:
diff --git a/goku-log/writer.go b/goku-log/writer.go
index ce4994e..41df536 100644
--- a/goku-log/writer.go
+++ b/goku-log/writer.go
@@ -1,4 +1,4 @@
-package goku_log
+package gokulog
import (
"bufio"
@@ -12,6 +12,7 @@ import (
"time"
)
+//MaxBufferd 最大缓存数值
const MaxBufferd = 1024 * 500
var (
@@ -22,6 +23,7 @@ var (
}
)
+//FileWriterByPeriod 文件输出对象
type FileWriterByPeriod struct {
wC chan *bytes.Buffer
dir string
@@ -34,6 +36,7 @@ type FileWriterByPeriod struct {
expire time.Duration
}
+//NewFileWriteBytePeriod 创建文件输出对象
func NewFileWriteBytePeriod() *FileWriterByPeriod {
w := &FileWriterByPeriod{
locker: sync.Mutex{},
@@ -49,6 +52,8 @@ func (w *FileWriterByPeriod) getExpire() time.Duration {
w.locker.Unlock()
return expire
}
+
+//Set 设置对象信息
func (w *FileWriterByPeriod) Set(dir, file string, period LogPeriod, expire time.Duration) {
fileName := strings.TrimSuffix(file, ".log")
@@ -59,6 +64,8 @@ func (w *FileWriterByPeriod) Set(dir, file string, period LogPeriod, expire time
w.expire = expire
w.locker.Unlock()
}
+
+//Open 打开文件
func (w *FileWriterByPeriod) Open() {
w.locker.Lock()
defer w.locker.Unlock()
@@ -74,6 +81,8 @@ func (w *FileWriterByPeriod) Open() {
w.enable = true
go w.do(ctx)
}
+
+//Close 关闭对象
func (w *FileWriterByPeriod) Close() {
isClose := false
diff --git a/goku-log/writer_test.go b/goku-log/writer_test.go
index 8b6fb70..f2d7be2 100644
--- a/goku-log/writer_test.go
+++ b/goku-log/writer_test.go
@@ -1,4 +1,4 @@
-package goku_log
+package gokulog
import (
"context"
diff --git a/goku-node/cmd/cluster.go b/goku-node/cmd/cluster.go
index 037e5a1..5415fd5 100644
--- a/goku-node/cmd/cluster.go
+++ b/goku-node/cmd/cluster.go
@@ -2,10 +2,12 @@ package cmd
import "github.com/eolinker/goku-api-gateway/server/entity"
+//CMD cmd
type CMD struct {
StatusCode string `json:"statuscode"`
}
+//ClusterConfig clusterConfig
type ClusterConfig struct {
CMD
Cluster *entity.ClusterInfo `json:"cluster"`
diff --git a/goku-node/cmd/config.go b/goku-node/cmd/config.go
index 419bfb7..4bf5f08 100644
--- a/goku-node/cmd/config.go
+++ b/goku-node/cmd/config.go
@@ -12,12 +12,12 @@ import (
"time"
)
-// 获取节点配置
+//GetConfig 获取节点配置
func GetConfig(listenPort int) (bool, *entity.ClusterInfo) {
client := &http.Client{
Timeout: time.Second * 10,
}
- addr := node_common.GetAdminUrl(fmt.Sprintf("/register?port=%d", listenPort))
+ addr := node_common.GetAdminURL(fmt.Sprintf("/register?port=%d", listenPort))
reader := bytes.NewReader([]byte(""))
request, err := http.NewRequest("GET", addr, reader)
if err != nil {
diff --git a/goku-node/cmd/heartbeat.go b/goku-node/cmd/heartbeat.go
index 3d5647c..8e55a55 100644
--- a/goku-node/cmd/heartbeat.go
+++ b/goku-node/cmd/heartbeat.go
@@ -9,6 +9,7 @@ import (
"time"
)
+//HeartBeatProid heartBeatProid
const HeartBeatProid = time.Second * 5
var (
@@ -16,6 +17,7 @@ var (
closeChan chan bool
)
+//Heartbeat heartBeat
func Heartbeat(port int) {
closeChan = make(chan bool)
serverPort = port
@@ -38,18 +40,19 @@ func Heartbeat(port int) {
func sendHeartBeat(port int) {
- addr := node_common.GetAdminUrl(fmt.Sprintf("node/heartbeat?port=%d", port))
+ addr := node_common.GetAdminURL(fmt.Sprintf("node/heartbeat?port=%d", port))
_, err := http.Get(addr)
if err != nil {
log.Warn("fail to send heartbeat:", err)
}
}
+//StopNode stopNode
func StopNode() {
close(closeChan)
log.Debug("stop node")
- addr := node_common.GetAdminUrl(fmt.Sprintf("node/stop?port=%d", serverPort))
+ addr := node_common.GetAdminURL(fmt.Sprintf("node/stop?port=%d", serverPort))
_, err := http.Get(addr)
if err != nil {
log.Warn("fail to send heartbeat:", err)
diff --git a/goku-node/cmd/request.go b/goku-node/cmd/request.go
index b469b4e..11fa123 100644
--- a/goku-node/cmd/request.go
+++ b/goku-node/cmd/request.go
@@ -12,12 +12,12 @@ import (
node_common "github.com/eolinker/goku-api-gateway/goku-node/node-common"
)
-// 新增报警信息
+//AddAlertMessage 新增报警信息
func AddAlertMessage(apiID int, apiName, requestURL, targetServer, targetURL, requestMethod, proxyMethod, headerList, queryParamList, formParamList, responseHeaderList string, alertPeriodType, alertCount, responseStatus int, isAlert string, strategyID string, strategyName, requestID string) (bool, string, error) {
client := &http.Client{
Timeout: time.Millisecond * 700,
}
- var data url.Values = url.Values{}
+ var data = url.Values{}
data.Add("requestID", requestID)
data.Add("apiID", strconv.Itoa(apiID))
data.Add("apiName", apiName)
@@ -38,7 +38,7 @@ func AddAlertMessage(apiID int, apiName, requestURL, targetServer, targetURL, re
data.Add("strategyID", strategyID)
data.Add("strategyName", strategyName)
data.Add("nodePort", strconv.Itoa(node_common.ListenPort))
- request, err := http.NewRequest("POST", node_common.GetAdminUrl("/alert/msg/add"), strings.NewReader(data.Encode()))
+ request, err := http.NewRequest("POST", node_common.GetAdminURL("/alert/msg/add"), strings.NewReader(data.Encode()))
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
if err != nil {
@@ -59,20 +59,20 @@ func AddAlertMessage(apiID int, apiName, requestURL, targetServer, targetURL, re
return true, "", nil
}
+//SendRequestToAlertAddress 发送告警请求
func SendRequestToAlertAddress(alertAddress, requestURL, targetServer, proxyURL, msg, apiName string, apiID int) (bool, string, error) {
if alertAddress == "" {
- return false, "[ERROR] Illegal alertAddress!", errors.New("[ERROR] Illegal alertAddress!")
- } else {
- _, err := url.Parse(alertAddress)
- if err != nil {
- return false, err.Error(), err
- }
+ return false, "[ERROR] Illegal alertAddress!", errors.New("[error] illegal alertAddress")
+ }
+ _, err := url.Parse(alertAddress)
+ if err != nil {
+ return false, err.Error(), err
}
client := &http.Client{
Timeout: time.Millisecond * 700,
}
now := time.Now().Format("2006-01-02 15:04:05")
- var data url.Values = url.Values{}
+ var data = url.Values{}
data.Add("requestURL", requestURL)
data.Add("targetServer", targetServer)
data.Add("targetURL", proxyURL)
diff --git a/goku-node/common/body-request.go b/goku-node/common/body-request.go
index 3af98bc..6eb64d0 100644
--- a/goku-node/common/body-request.go
+++ b/goku-node/common/body-request.go
@@ -16,11 +16,12 @@ import (
const defaultMultipartMemory = 32 << 20 // 32 MB
var (
- _ErrorNotForm = errors.New("contentType is not Form")
- _ErrorNotMultipart = errors.New("contentType is not Multipart")
- _ErrorNotAllowRaw = errors.New("contentType is not allow Raw")
+ errNotForm = errors.New("contentType is not Form")
+ errNotMultipart = errors.New("contentType is not Multipart")
+ errNotAllowRaw = errors.New("contentType is not allow Raw")
)
+//BodyRequestHandler body request handler
type BodyRequestHandler struct {
form url.Values
rawbody []byte
@@ -32,6 +33,7 @@ type BodyRequestHandler struct {
isWriteRaw bool
}
+//Files files
func (b *BodyRequestHandler) Files() (map[string]*goku_plugin.FileHeader, error) {
err := b.Parse()
@@ -42,6 +44,8 @@ func (b *BodyRequestHandler) Files() (map[string]*goku_plugin.FileHeader, error)
return b.files, nil
}
+
+//Parse parse
func (b *BodyRequestHandler) Parse() error {
if b.isInit {
@@ -109,6 +113,8 @@ func (b *BodyRequestHandler) Parse() error {
b.isInit = true
return nil
}
+
+//GetForm get form
func (b *BodyRequestHandler) GetForm(key string) string {
contentType, _, _ := mime.ParseMediaType(b.contentType)
@@ -123,6 +129,7 @@ func (b *BodyRequestHandler) GetForm(key string) string {
return b.form.Get(key)
}
+//GetFile getFile
func (b *BodyRequestHandler) GetFile(key string) (file *goku_plugin.FileHeader, has bool) {
contentType, _, _ := mime.ParseMediaType(b.contentType)
@@ -142,11 +149,12 @@ func (b *BodyRequestHandler) GetFile(key string) (file *goku_plugin.FileHeader,
return f, has
}
+//SetToForm setToForm
func (b *BodyRequestHandler) SetToForm(key, value string) error {
contentType, _, _ := mime.ParseMediaType(b.contentType)
if contentType != goku_plugin.FormData && contentType != goku_plugin.MultipartForm {
- return _ErrorNotForm
+ return errNotForm
}
err := b.Parse()
@@ -164,10 +172,11 @@ func (b *BodyRequestHandler) SetToForm(key, value string) error {
return nil
}
+//AddForm addForm
func (b *BodyRequestHandler) AddForm(key, value string) error {
contentType, _, _ := mime.ParseMediaType(b.contentType)
if contentType != goku_plugin.FormData && contentType != goku_plugin.MultipartForm {
- return _ErrorNotForm
+ return errNotForm
}
err := b.Parse()
if err != nil {
@@ -182,11 +191,12 @@ func (b *BodyRequestHandler) AddForm(key, value string) error {
return nil
}
+//AddFile 新建文件参数
func (b *BodyRequestHandler) AddFile(key string, file *goku_plugin.FileHeader) error {
contentType, _, _ := mime.ParseMediaType(b.contentType)
if contentType != goku_plugin.FormData && contentType != goku_plugin.MultipartForm {
- return _ErrorNotMultipart
+ return errNotMultipart
}
err := b.Parse()
if err != nil {
@@ -205,6 +215,7 @@ func (b *BodyRequestHandler) AddFile(key string, file *goku_plugin.FileHeader) e
return nil
}
+//Clone 请求克隆
func (b *BodyRequestHandler) Clone() *BodyRequestHandler {
rawbody, _ := b.RawBody()
@@ -212,10 +223,13 @@ func (b *BodyRequestHandler) Clone() *BodyRequestHandler {
return NewBodyRequestHandler(b.contentType, rawbody)
}
+
+//ContentType contentType
func (b *BodyRequestHandler) ContentType() string {
return b.contentType
}
+//BodyForm 获取body参数
func (b *BodyRequestHandler) BodyForm() (url.Values, error) {
err := b.Parse()
@@ -225,6 +239,7 @@ func (b *BodyRequestHandler) BodyForm() (url.Values, error) {
return b.form, nil
}
+//Encode encode
func (b *BodyRequestHandler) Encode() error {
if b.isWriteRaw {
return nil
@@ -277,6 +292,7 @@ func (b *BodyRequestHandler) Encode() error {
return nil
}
+//RawBody rawBody
func (b *BodyRequestHandler) RawBody() ([]byte, error) {
err := b.Encode()
@@ -287,11 +303,12 @@ func (b *BodyRequestHandler) RawBody() ([]byte, error) {
}
+//SetForm 设置表单参数
func (b *BodyRequestHandler) SetForm(values url.Values) error {
contentType, _, _ := mime.ParseMediaType(b.contentType)
if contentType != goku_plugin.FormData && contentType != goku_plugin.MultipartForm {
- return _ErrorNotForm
+ return errNotForm
}
b.Parse()
b.form = values
@@ -300,11 +317,12 @@ func (b *BodyRequestHandler) SetForm(values url.Values) error {
return nil
}
+//SetFile 设置文件参数
func (b *BodyRequestHandler) SetFile(files map[string]*goku_plugin.FileHeader) error {
contentType, _, _ := mime.ParseMediaType(b.contentType)
if contentType != goku_plugin.FormData && contentType != goku_plugin.MultipartForm {
- return _ErrorNotForm
+ return errNotForm
}
b.Parse()
b.files = files
@@ -314,6 +332,7 @@ func (b *BodyRequestHandler) SetFile(files map[string]*goku_plugin.FileHeader) e
return nil
}
+//SetRaw 设置Raw
func (b *BodyRequestHandler) SetRaw(contentType string, body []byte) {
b.rawbody, b.contentType, b.isInit, b.isWriteRaw = body, contentType, false, true
@@ -322,6 +341,7 @@ func (b *BodyRequestHandler) SetRaw(contentType string, body []byte) {
}
+//NewBodyRequestHandler 创建body请求处理器
func NewBodyRequestHandler(contentType string, body []byte) *BodyRequestHandler {
b := new(BodyRequestHandler)
b.SetRaw(contentType, body)
diff --git a/goku-node/common/body.go b/goku-node/common/body.go
index 37fd4c1..a740282 100644
--- a/goku-node/common/body.go
+++ b/goku-node/common/body.go
@@ -1,9 +1,11 @@
package common
+//BodyHandler body处理器
type BodyHandler struct {
body []byte
}
+//GetBody 获取body内容
func (r *BodyHandler) GetBody() []byte {
if r == nil {
return nil
@@ -11,10 +13,12 @@ func (r *BodyHandler) GetBody() []byte {
return r.body
}
+//SetBody 设置body内容
func (r *BodyHandler) SetBody(body []byte) {
r.body = body
}
+//NewBodyHandler 创建body处理器
func NewBodyHandler(body []byte) *BodyHandler {
return &BodyHandler{body: body}
}
diff --git a/goku-node/common/context.go b/goku-node/common/context.go
index 0e73a65..89e6c14 100644
--- a/goku-node/common/context.go
+++ b/goku-node/common/context.go
@@ -9,6 +9,7 @@ import (
var _ goku_plugin.ContextProxy = (*Context)(nil)
+//Context context
type Context struct {
w http.ResponseWriter
*CookiesHandler
@@ -19,27 +20,35 @@ type Context struct {
ProxyRequest *Request
ProxyResponseHandler *ResponseReader
Body []byte
- strategyId string
+ strategyID string
strategyName string
- apiId int
- requestId string
+ apiID int
+ requestID string
finalTargetServer string
retryTargetServers string
}
+//FinalTargetServer 获取最终目标转发服务器
func (ctx *Context) FinalTargetServer() string {
return ctx.finalTargetServer
}
+
+//SetFinalTargetServer 设置最终目标服务器
func (ctx *Context) SetFinalTargetServer(finalTargetServer string) {
ctx.finalTargetServer = finalTargetServer
}
+
+//RetryTargetServers 重试目标服务器
func (ctx *Context) RetryTargetServers() string {
return ctx.retryTargetServers
}
+
+//SetRetryTargetServers 设置重试目标服务器
func (ctx *Context) SetRetryTargetServers(retryTargetServers string) {
ctx.retryTargetServers = retryTargetServers
}
+//Finish 请求结束
func (ctx *Context) Finish() (n int, statusCode int) {
header := ctx.PriorityHeader.header
@@ -96,11 +105,14 @@ func (ctx *Context) Finish() (n int, statusCode int) {
n, _ = ctx.w.Write(ctx.Body)
return n, statusCode
}
+
+//RequestId 获取请求ID
func (ctx *Context) RequestId() string {
- return ctx.requestId
+ return ctx.requestID
}
-func NewContext(r *http.Request, requestId string, w http.ResponseWriter) *Context {
+//NewContext 创建context
+func NewContext(r *http.Request, requestID string, w http.ResponseWriter) *Context {
requestreader := NewRequestReader(r)
return &Context{
CookiesHandler: newCookieHandle(r.Header),
@@ -110,10 +122,12 @@ func NewContext(r *http.Request, requestId string, w http.ResponseWriter) *Conte
RequestOrg: requestreader,
ProxyRequest: NewRequest(requestreader),
ProxyResponseHandler: nil,
- requestId: requestId,
+ requestID: requestID,
w: w,
}
}
+
+//SetProxyResponse 设置转发响应
func (ctx *Context) SetProxyResponse(response *http.Response) {
ctx.ProxyResponseHandler = newResponseReader(response)
@@ -136,39 +150,57 @@ func (ctx *Context) Write(w http.ResponseWriter) {
}
+//GetBody 获取body内容
func (ctx *Context) GetBody() []byte {
return ctx.Body
}
+
+//SetBody 设置body内容
func (ctx *Context) SetBody(data []byte) {
ctx.Body = data
}
+//ProxyResponse 转发响应
func (ctx *Context) ProxyResponse() goku_plugin.ResponseReader {
return ctx.ProxyResponseHandler
}
+//StrategyId 获取策略ID
func (ctx *Context) StrategyId() string {
- return ctx.strategyId
+ return ctx.strategyID
}
-func (ctx *Context) SetStrategyId(strategyId string) {
- ctx.strategyId = strategyId
+
+//SetStrategyId 设置策略ID
+func (ctx *Context) SetStrategyId(strategyID string) {
+ ctx.strategyID = strategyID
}
+
+//StrategyName 获取策略名称
func (ctx *Context) StrategyName() string {
return ctx.strategyName
}
+
+//SetStrategyName 设置策略名称
func (ctx *Context) SetStrategyName(strategyName string) {
ctx.strategyName = strategyName
}
+
+//ApiID 获取接口ID
func (ctx *Context) ApiID() int {
- return ctx.apiId
+ return ctx.apiID
}
-func (ctx *Context) SetApiID(apiId int) {
- ctx.apiId = apiId
+
+//SetAPIID 设置接口ID
+func (ctx *Context) SetAPIID(apiID int) {
+ ctx.apiID = apiID
}
+
+//Request 获取请求原始数据
func (ctx *Context) Request() goku_plugin.RequestReader {
return ctx.RequestOrg
}
+//Proxy 获取代理请求
func (ctx *Context) Proxy() goku_plugin.Request {
return ctx.ProxyRequest
}
diff --git a/goku-node/common/cookies.go b/goku-node/common/cookies.go
index 177f771..8ecf4eb 100644
--- a/goku-node/common/cookies.go
+++ b/goku-node/common/cookies.go
@@ -2,18 +2,22 @@ package common
import "net/http"
+//CookiesHandler cookies处理器
type CookiesHandler struct {
req http.Request
}
+//AddCookie 新增cookie
func (cs *CookiesHandler) AddCookie(c *http.Cookie) {
cs.req.AddCookie(c)
}
+//Cookie 获取cookie
func (cs *CookiesHandler) Cookie(name string) (*http.Cookie, error) {
return cs.req.Cookie(name)
}
+//Cookies 获取cookies
func (cs *CookiesHandler) Cookies() []*http.Cookie {
return cs.req.Cookies()
}
diff --git a/goku-node/common/header.go b/goku-node/common/header.go
index 8ff74bc..a522e9c 100644
--- a/goku-node/common/header.go
+++ b/goku-node/common/header.go
@@ -6,10 +6,12 @@ import (
"net/url"
)
+//Header header
type Header struct {
header http.Header
}
+//Headers 返回headers
func (h *Header) Headers() http.Header {
n := make(http.Header)
@@ -35,21 +37,28 @@ func (h *Header) String() string {
//}
//return string(data)
}
+
+//SetHeader 设置请求头
func (h *Header) SetHeader(key, value string) {
h.header.Set(key, value)
}
+//AddHeader 新增请求头
func (h *Header) AddHeader(key, value string) {
h.header.Add(key, value)
}
+//DelHeader 删除请求头
func (h *Header) DelHeader(key string) {
h.header.Del(key)
}
+//GetHeader 通过名字获取请求头
func (h *Header) GetHeader(name string) string {
return h.header.Get(name)
}
+
+//NewHeader 创建header请求头
func NewHeader(header http.Header) *Header {
if header == nil {
header = make(http.Header)
@@ -59,12 +68,14 @@ func NewHeader(header http.Header) *Header {
}
}
+//PriorityHeader proorityHeader
type PriorityHeader struct {
*Header
setHeader *Header
appendHeader *Header
}
+//Set set
func (h *PriorityHeader) Set() goku_plugin.Header {
if h.setHeader == nil {
h.setHeader = NewHeader(nil)
@@ -72,6 +83,7 @@ func (h *PriorityHeader) Set() goku_plugin.Header {
return h.setHeader
}
+//Append append
func (h *PriorityHeader) Append() goku_plugin.Header {
if h.appendHeader == nil {
h.appendHeader = NewHeader(nil)
@@ -79,6 +91,7 @@ func (h *PriorityHeader) Append() goku_plugin.Header {
return h.setHeader
}
+//NewPriorityHeader 创建优先级header
func NewPriorityHeader() *PriorityHeader {
return &PriorityHeader{
Header: NewHeader(nil),
diff --git a/goku-node/common/request-reader.go b/goku-node/common/request-reader.go
index beaa9de..bd00b23 100644
--- a/goku-node/common/request-reader.go
+++ b/goku-node/common/request-reader.go
@@ -5,23 +5,28 @@ import (
"net/url"
)
+//RequestReader 请求header
type RequestReader struct {
*Header
*BodyRequestHandler
req *http.Request
}
+//Proto 获取协议
func (r *RequestReader) Proto() string {
return r.req.Proto
}
+//NewRequestReader 获取新请求header
func NewRequestReader(req *http.Request) *RequestReader {
r := new(RequestReader)
r.req = req
r.ParseRequest()
return r
}
-func (r *RequestReader) ParseRequest() () {
+
+//ParseRequest 解析请求
+func (r *RequestReader) ParseRequest() {
r.Header = NewHeader(r.req.Header)
@@ -38,30 +43,37 @@ func (r *RequestReader) ParseRequest() () {
// todo
}
+//Cookie 获取cookie
func (r *RequestReader) Cookie(name string) (*http.Cookie, error) {
return r.req.Cookie(name)
}
+//Cookies 获取cookies
func (r *RequestReader) Cookies() []*http.Cookie {
return r.req.Cookies()
}
+//Method 获取方法
func (r *RequestReader) Method() string {
return r.req.Method
}
+//URL 获取URL
func (r *RequestReader) URL() *url.URL {
return r.req.URL
}
+//RequestURI 获取请求URI
func (r *RequestReader) RequestURI() string {
return r.req.RequestURI
}
+//Host 获取host
func (r *RequestReader) Host() string {
return r.req.Host
}
+//RemoteAddr 获取客户端地址
func (r *RequestReader) RemoteAddr() string {
return r.req.RemoteAddr
}
diff --git a/goku-node/common/request.go b/goku-node/common/request.go
index eb01152..9048fe2 100644
--- a/goku-node/common/request.go
+++ b/goku-node/common/request.go
@@ -2,7 +2,7 @@ package common
import "net/url"
-// 转发内容
+//Request 转发内容
type Request struct {
*Header
*CookiesHandler
@@ -13,22 +13,32 @@ type Request struct {
Method string
}
+//TargetURL 转发URL
func (r *Request) TargetURL() string {
return r.targetURL
}
+
+//SetTargetURL 设置转发URL
func (r *Request) SetTargetURL(targetURL string) {
r.targetURL = targetURL
}
+
+//TargetServer 获取转发服务器地址
func (r *Request) TargetServer() string {
return r.targetServer
}
+
+//SetTargetServer 设置转发服务器地址
func (r *Request) SetTargetServer(targetServer string) {
r.targetServer = targetServer
}
+
+//Querys 获取query参数
func (r *Request) Querys() url.Values {
return r.querys
}
+//NewRequest 新请求
func NewRequest(r *RequestReader) *Request {
if r == nil {
return nil
diff --git a/goku-node/common/response.go b/goku-node/common/response.go
index 290c772..d56e682 100644
--- a/goku-node/common/response.go
+++ b/goku-node/common/response.go
@@ -5,6 +5,7 @@ import (
"net/http"
)
+//ResponseReader 响应读取器
type ResponseReader struct {
*CookiesHandler
*Header
diff --git a/goku-node/common/status.go b/goku-node/common/status.go
index 0e430a5..5800a54 100644
--- a/goku-node/common/status.go
+++ b/goku-node/common/status.go
@@ -1,22 +1,27 @@
package common
+//StatusHandler 状态码处理器
type StatusHandler struct {
code int
status string
}
+//SetStatus 设置状态
func (s *StatusHandler) SetStatus(code int, status string) {
s.code, s.status = code, status
}
+//StatusCode 获取状态码
func (s *StatusHandler) StatusCode() int {
return s.code
}
+//Status 获取状态描述
func (s *StatusHandler) Status() string {
return s.status
}
+//NewStatusHandler 创建状态处理器
func NewStatusHandler() *StatusHandler {
return new(StatusHandler)
}
diff --git a/goku-node/common/store.go b/goku-node/common/store.go
index 1791f8b..bd75052 100644
--- a/goku-node/common/store.go
+++ b/goku-node/common/store.go
@@ -2,28 +2,34 @@ package common
import goku_plugin "github.com/eolinker/goku-plugin"
+//Store 存储器
type Store struct {
value interface{}
}
+//Set set
func (s *Store) Set(value interface{}) {
s.value = value
}
+//Get get
func (s *Store) Get() (value interface{}) {
return s.value
}
+//StoreHandler 存储处理器
type StoreHandler struct {
Cache map[string]interface{}
Stores map[string]goku_plugin.Store
CurrentPluginName string
}
+//SetPlugin 设置插件
func (s *StoreHandler) SetPlugin(name string) {
s.CurrentPluginName = name
}
+//SetCache 设置缓存
func (s *StoreHandler) SetCache(name string, value interface{}) {
if s.Cache == nil {
s.Cache = make(map[string]interface{})
@@ -31,6 +37,7 @@ func (s *StoreHandler) SetCache(name string, value interface{}) {
s.Cache[name] = value
}
+//GetCache 获取缓存
func (s *StoreHandler) GetCache(name string) (value interface{}, has bool) {
if s.Cache == nil {
return nil, false
@@ -39,6 +46,7 @@ func (s *StoreHandler) GetCache(name string) (value interface{}, has bool) {
return
}
+//Store 存储器
func (s *StoreHandler) Store() goku_plugin.Store {
if s.Stores == nil {
s.Stores = make(map[string]goku_plugin.Store)
@@ -52,6 +60,7 @@ func (s *StoreHandler) Store() goku_plugin.Store {
return store
}
+//NewStoreHandler 创建存储处理器
func NewStoreHandler() *StoreHandler {
return new(StoreHandler)
}
diff --git a/goku-node/driver.go b/goku-node/driver.go
index ec9963d..3845142 100644
--- a/goku-node/driver.go
+++ b/goku-node/driver.go
@@ -1,6 +1,8 @@
-package goku_node
+package gokunode
+
import (
+ // 驱动加载
_ "github.com/eolinker/goku-api-gateway/goku-node/manager/service-manager"
_ "github.com/eolinker/goku-api-gateway/goku-service/driver/consul"
_ "github.com/eolinker/goku-api-gateway/goku-service/driver/eureka"
diff --git a/goku-node/handler/handler.go b/goku-node/handler/handler.go
index 9091b6d..789eb2c 100644
--- a/goku-node/handler/handler.go
+++ b/goku-node/handler/handler.go
@@ -4,6 +4,7 @@ import (
"net/http"
)
+//Entry entry
type Entry struct {
Pattern string
HandlerFunc func(w http.ResponseWriter, r *http.Request)
@@ -12,6 +13,8 @@ type Entry struct {
func init() {
}
+
+//Handler handler
func Handler() []Entry {
return []Entry{
diff --git a/goku-node/handler/update.go b/goku-node/handler/update.go
index ef5020a..b8d0af9 100644
--- a/goku-node/handler/update.go
+++ b/goku-node/handler/update.go
@@ -2,7 +2,7 @@ package handler
import (
"encoding/json"
- . "github.com/eolinker/goku-api-gateway/common/version"
+ v "github.com/eolinker/goku-api-gateway/common/version"
"github.com/eolinker/goku-api-gateway/goku-node/manager/updater"
"net/http"
)
@@ -14,7 +14,7 @@ func gokuCheckUpdate(w http.ResponseWriter, r *http.Request) {
resultInfo := map[string]interface{}{
"type": "update",
"statusCode": "000000",
- "version": Version,
+ "version": v.Version,
}
resultStr, _ := json.Marshal(resultInfo)
diff --git a/goku-node/manager/api-manager/api.go b/goku-node/manager/api-manager/api.go
index ffe8992..b2452e5 100644
--- a/goku-node/manager/api-manager/api.go
+++ b/goku-node/manager/api-manager/api.go
@@ -1,4 +1,4 @@
-package api_manager
+package apimanager
import (
"sync"
@@ -14,22 +14,22 @@ func init() {
// apiList: api列表全局变量
var (
- apiList map[int]*entity.Api
+ apiList map[int]*entity.API
locker sync.RWMutex
)
-//GetAPI
-func GetAPI(id int) (*entity.Api, bool) {
+//GetAPI 通过id获取API信息
+func GetAPI(id int) (*entity.API, bool) {
locker.RLock()
defer locker.RUnlock()
a, has := apiList[id]
return a, has
}
-//GetAPI
-func GetAPIs(ids []int) []*entity.Api {
+//GetAPIs 获取接口信息列表
+func GetAPIs(ids []int) []*entity.API {
- apis := make([]*entity.Api, 0, len(ids))
+ apis := make([]*entity.API, 0, len(ids))
locker.RLock()
defer locker.RUnlock()
@@ -42,14 +42,14 @@ func GetAPIs(ids []int) []*entity.Api {
return apis
}
-func reset(list map[int]*entity.Api) {
+func reset(list map[int]*entity.API) {
locker.Lock()
defer locker.Unlock()
apiList = list
}
func load() {
- apis, e := dao_api.GetAllApi()
+ apis, e := dao_api.GetAllAPI()
if e != nil {
return
}
diff --git a/goku-node/manager/balance-manager/balance.go b/goku-node/manager/balance-manager/balance.go
index e6f0749..6bf28c2 100644
--- a/goku-node/manager/balance-manager/balance.go
+++ b/goku-node/manager/balance-manager/balance.go
@@ -1,4 +1,4 @@
-package balance_manager
+package balancemanager
import (
"encoding/json"
@@ -17,6 +17,7 @@ func init() {
updater.Add(loadBalanceInfo, 3, "goku_balance")
}
+//Get get
func Get(name string) (application.IHttpApplication, bool) {
return balance.GetByName(name)
diff --git a/goku-node/manager/config-manager/field.go b/goku-node/manager/config-manager/field.go
index b025432..eee660d 100644
--- a/goku-node/manager/config-manager/field.go
+++ b/goku-node/manager/config-manager/field.go
@@ -1,5 +1,6 @@
-package config_manager
+package configmanager
+//AccessField access字段
type AccessField struct {
Name string `json:"name"`
Select bool `json:"select"`
diff --git a/goku-node/manager/config-manager/log.go b/goku-node/manager/config-manager/log.go
index d052c22..58e5f66 100644
--- a/goku-node/manager/config-manager/log.go
+++ b/goku-node/manager/config-manager/log.go
@@ -1,4 +1,4 @@
-package config_manager
+package configmanager
import (
"encoding/json"
@@ -11,8 +11,10 @@ import (
)
const (
+ //AccessLog access日志
AccessLog = "access"
- NodeLog = "node"
+ //NodeLog 节点日志
+ NodeLog = "node"
)
func init() {
@@ -39,6 +41,8 @@ func defaultNodeAppLogConfig() *entity.LogConfig {
Period: "hour",
}
}
+
+//InitLog 初始化日志
func InitLog() {
reloadLogConfig()
}
diff --git a/goku-node/manager/gateway-manager/gateway.go b/goku-node/manager/gateway-manager/gateway.go
index d1ac8ae..2680136 100644
--- a/goku-node/manager/gateway-manager/gateway.go
+++ b/goku-node/manager/gateway-manager/gateway.go
@@ -1,4 +1,4 @@
-package gateway_manager
+package gatewaymanager
import (
"strconv"
@@ -16,24 +16,28 @@ var (
_AlertInfo = "{\"alertAddr\":\"\",\"alertPeriodType\":0,\"logPath\":\"./log/apiAlert\",\"receiverList\":\"\"}"
)
+//GetUpdatePeriod 获取更新周期
func GetUpdatePeriod() int {
locker.RLock()
defer locker.RUnlock()
return _UpdatePeriod
}
+//GetAlertStatus 获取告警状态
func GetAlertStatus() int {
locker.RLock()
defer locker.RUnlock()
return _AlertStatus
}
+//GetAlertInfo 获取告警信息
func GetAlertInfo() string {
locker.RLock()
defer locker.RUnlock()
return _AlertInfo
}
+//LoadGatewayConfig 加载网关配置
func LoadGatewayConfig() {
code, period := dao_gateway.GetGatewayBaseInfo()
alertInfo, alrtStatus := dao_gateway.GetGatewayAlertInfo()
@@ -45,6 +49,7 @@ func LoadGatewayConfig() {
_AlertInfo = alertInfo
}
+//IsSucess 是否成功
func IsSucess(statusCode int) bool {
locker.RLock()
defer locker.RUnlock()
diff --git a/goku-node/manager/plugin-manager/errorCode.go b/goku-node/manager/plugin-manager/errorCode.go
index 129790c..e935aa1 100644
--- a/goku-node/manager/plugin-manager/errorCode.go
+++ b/goku-node/manager/plugin-manager/errorCode.go
@@ -1,6 +1,7 @@
-package plugin_manager
+package pluginmanager
const (
+ //LoadOk load ok
LoadOk = iota
LoadFileError
LoadLookupError
diff --git a/goku-node/manager/plugin-manager/handle.go b/goku-node/manager/plugin-manager/handle.go
index c00a8ae..6aec556 100644
--- a/goku-node/manager/plugin-manager/handle.go
+++ b/goku-node/manager/plugin-manager/handle.go
@@ -1,19 +1,20 @@
-package plugin_manager
+package pluginmanager
import (
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
-// 获取默认插件列表
+//GetDefaultPlugins 获取默认插件列表
func GetDefaultPlugins() []*entity.PluginHandlerExce {
return defaultPlugins
}
-// 获取默认插件列表
+//GetBeforPlugins 获取默认插件列表
func GetBeforPlugins() []*entity.PluginHandlerExce {
return beforPlugins
}
+//Check check
func Check(name string) (int, error) {
return globalPluginManager.check(name)
}
diff --git a/goku-node/manager/plugin-manager/manager.go b/goku-node/manager/plugin-manager/manager.go
index bc285a5..8c5ef15 100644
--- a/goku-node/manager/plugin-manager/manager.go
+++ b/goku-node/manager/plugin-manager/manager.go
@@ -1,4 +1,4 @@
-package plugin_manager
+package pluginmanager
import (
"sort"
@@ -16,7 +16,7 @@ var (
beforPlugins []*entity.PluginHandlerExce
)
-// 获取单一插件handle
+//GetPluginHandle 获取单一插件handle
func GetPluginHandle(name string) *entity.PluginFactoryHandler {
locker.RLock()
handle := pluginHandles[name]
diff --git a/goku-node/manager/plugin-manager/plugin.go b/goku-node/manager/plugin-manager/plugin.go
index f4dc7f6..8b3cf2c 100644
--- a/goku-node/manager/plugin-manager/plugin.go
+++ b/goku-node/manager/plugin-manager/plugin.go
@@ -1,4 +1,4 @@
-package plugin_manager
+package pluginmanager
import (
"github.com/eolinker/goku-api-gateway/goku-node/manager/updater"
diff --git a/goku-node/manager/plugin-manager/pluginload.go b/goku-node/manager/plugin-manager/pluginload.go
index 058a506..7f43f6c 100644
--- a/goku-node/manager/plugin-manager/pluginload.go
+++ b/goku-node/manager/plugin-manager/pluginload.go
@@ -1,4 +1,4 @@
-package plugin_manager
+package pluginmanager
import (
"fmt"
@@ -7,8 +7,8 @@ import (
"reflect"
"sync"
- goku_plugin "github.com/eolinker/goku-plugin"
node_common "github.com/eolinker/goku-api-gateway/goku-node/node-common"
+ goku_plugin "github.com/eolinker/goku-plugin"
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
@@ -36,7 +36,7 @@ func (m *_GlodPluginManager) check(name string) (int, error) {
return code, err
}
- _, e, errorCode := m.loadPlugin(name)
+ _, errorCode, e := m.loadPlugin(name)
return errorCode, e
}
@@ -59,14 +59,14 @@ func (m *_GlodPluginManager) getPluginHandle(name string) (goku_plugin.PluginFac
return p, has
}
-// 获取所有插件列表
+//LoadPlugin 获取所有插件列表
func LoadPlugin(pis map[string]*entity.PluginInfo) (allFactory map[string]*entity.PluginFactoryHandler, defaultPlugins []*entity.PluginHandlerExce, beforMatchs []*entity.PluginHandlerExce) {
plugins := make(map[string]*entity.PluginFactoryHandler)
def := make([]*entity.PluginHandlerExce, 0, len(pis))
before := make([]*entity.PluginHandlerExce, 0, len(pis))
for key, value := range pis {
- handle, err, _ := globalPluginManager.loadPlugin(key)
+ handle, _, err := globalPluginManager.loadPlugin(key)
if err != nil {
goku_plugin.Warn("LoadPlugin:", err.Error())
continue
@@ -105,18 +105,18 @@ func LoadPlugin(pis map[string]*entity.PluginInfo) (allFactory map[string]*entit
return plugins, def, before
}
-// 加载动态库
-func (m *_GlodPluginManager) loadPlugin(name string) (goku_plugin.PluginFactory, error, int) {
+//loadPlugin 加载动态库
+func (m *_GlodPluginManager) loadPlugin(name string) (goku_plugin.PluginFactory, int, error) {
handle, has := m.getPluginHandle(name)
if has {
- return handle, nil, 0
+ return handle, 0, nil
}
m.gloadPluginLocker.Lock()
defer m.gloadPluginLocker.Unlock()
handle, has = m.gloadPlugin[name]
if has {
- return handle, nil, LoadOk
+ return handle, LoadOk, nil
}
path, _ := filepath.Abs(fmt.Sprintf("plugin/%s.so", name))
@@ -125,7 +125,7 @@ func (m *_GlodPluginManager) loadPlugin(name string) (goku_plugin.PluginFactory,
e := fmt.Errorf("The plugin file named '%s.so' can not be found in plugin:%s ", name, err.Error())
m.errors[name] = e
m.errorCodes[name] = LoadFileError
- return nil, e, LoadFileError
+ return nil, LoadFileError, e
}
//structName := strings.Replace(name, "-", "_", -1)
@@ -139,7 +139,7 @@ func (m *_GlodPluginManager) loadPlugin(name string) (goku_plugin.PluginFactory,
m.errors[name] = e
m.errorCodes[name] = LoadLookupError
- return nil, e, LoadLookupError
+ return nil, LoadLookupError, e
}
vp, ok := v.(func() goku_plugin.PluginFactory)
@@ -147,18 +147,18 @@ func (m *_GlodPluginManager) loadPlugin(name string) (goku_plugin.PluginFactory,
e := fmt.Errorf("The builder func can not implemented interface named goku_plugin.PluginFactory:%s ", name)
m.errors[name] = e
m.errorCodes[name] = LoadInterFaceError
- return nil, e, LoadInterFaceError
+ return nil, LoadInterFaceError, e
}
factory := vp()
if factory == nil || reflect.ValueOf(factory).IsNil() {
e := fmt.Errorf("The builder result is nil:%s ", name)
m.errors[name] = e
m.errorCodes[name] = LoadInterFaceError
- return nil, e, LoadInterFaceError
+ return nil, LoadInterFaceError, e
}
m.gloadPlugin[name] = factory
m.errorCodes[name] = LoadOk
m.errors[name] = nil
- return factory, nil, LoadOk
+ return factory, LoadOk, nil
}
diff --git a/goku-node/manager/service-manager/service.go b/goku-node/manager/service-manager/service.go
index 3cce722..1fc5f64 100644
--- a/goku-node/manager/service-manager/service.go
+++ b/goku-node/manager/service-manager/service.go
@@ -1,4 +1,4 @@
-package service_manager
+package servicemanager
import (
"encoding/json"
diff --git a/goku-node/manager/strategy-api-manager/apis.go b/goku-node/manager/strategy-api-manager/apis.go
index 39bf8fd..fdda1dd 100644
--- a/goku-node/manager/strategy-api-manager/apis.go
+++ b/goku-node/manager/strategy-api-manager/apis.go
@@ -1,12 +1,12 @@
-package strategy_api_manager
+package strategyapimanager
import entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
-type _ApiMap struct {
- apis map[int]*entity.StrategyApi
+type _APIMap struct {
+ apis map[int]*entity.StrategyAPI
}
-func (m *_ApiMap) Get(id int) (*entity.StrategyApi, bool) {
+func (m *_APIMap) Get(id int) (*entity.StrategyAPI, bool) {
api, has := m.apis[id]
return api, has
}
diff --git a/goku-node/manager/strategy-api-manager/match.go b/goku-node/manager/strategy-api-manager/match.go
index 6ff4acd..bf167ad 100644
--- a/goku-node/manager/strategy-api-manager/match.go
+++ b/goku-node/manager/strategy-api-manager/match.go
@@ -1,4 +1,4 @@
-package strategy_api_manager
+package strategyapimanager
import (
"github.com/eolinker/goku-api-gateway/utils"
@@ -9,13 +9,14 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
-func CheckApiFromStrategy(strategyId, requestPath string, requestMethod string) (*entity.ApiExtend, string, []string, bool) {
- apiMap, has := getAPis(strategyId)
+//CheckAPIFromStrategy 判断接口是否在策略中
+func CheckAPIFromStrategy(strategyID, requestPath string, requestMethod string) (*entity.APIExtend, string, []string, bool) {
+ apiMap, has := getAPis(strategyID)
if !has {
return nil, "", nil, false
}
- for _, strategyApi := range apiMap.apis {
- apiInfo, has := api_manager.GetAPI(strategyApi.ApiId)
+ for _, strategyAPI := range apiMap.apis {
+ apiInfo, has := api_manager.GetAPI(strategyAPI.APIID)
if !has {
continue
}
@@ -28,17 +29,16 @@ func CheckApiFromStrategy(strategyId, requestPath string, requestMethod string)
if isMatch {
method := strings.ToUpper(apiInfo.RequestMethod)
if strings.Contains(method, requestMethod) {
- apiextend := &entity.ApiExtend{Api: apiInfo}
+ apiextend := &entity.APIExtend{API: apiInfo}
- if strategyApi.Target != "" {
- apiextend.Target = strategyApi.Target
+ if strategyAPI.Target != "" {
+ apiextend.Target = strategyAPI.Target
} else {
apiextend.Target = apiInfo.BalanceName
}
apiextend.Target = utils.TrimSuffixAll(apiextend.Target, "/")
- //apiextend.TargetServer = balance_manager.ParseTargetServer(apiextend.Target)
return apiextend, splitURL, param, true
}
}
diff --git a/goku-node/manager/strategy-api-manager/strategy-api.go b/goku-node/manager/strategy-api-manager/strategy-api.go
index 79d82b2..405e915 100644
--- a/goku-node/manager/strategy-api-manager/strategy-api.go
+++ b/goku-node/manager/strategy-api-manager/strategy-api.go
@@ -1,4 +1,4 @@
-package strategy_api_manager
+package strategyapimanager
import (
"sync"
@@ -9,50 +9,50 @@ import (
)
func init() {
- updater.Add(loadStategyApi, 6, "goku_conn_strategy_api", "goku_gateway_strategy", "goku_gateway_api")
+ updater.Add(loadStategyAPI, 6, "goku_conn_strategy_api", "goku_gateway_strategy", "goku_gateway_api")
}
var (
- apiOfStrategy = make(map[string]*_ApiMap)
+ apiOfStrategy = make(map[string]*_APIMap)
apiLocker sync.RWMutex
)
//GetAPIForStategy 获取指定策略、API 对应的 配置
-func GetAPIForStategy(stategyId string, apiId int) (*entity.StrategyApi, bool) {
- apis, has := getAPis(stategyId)
+func GetAPIForStategy(stategyID string, apiID int) (*entity.StrategyAPI, bool) {
+ apis, has := getAPis(stategyID)
if !has {
return nil, false
}
- return apis.Get(apiId)
+ return apis.Get(apiID)
}
-func getAPis(strategyId string) (*_ApiMap, bool) {
- apis, has := apiOfStrategy[strategyId]
+func getAPis(strategyID string) (*_APIMap, bool) {
+ apis, has := apiOfStrategy[strategyID]
return apis, has
}
-func resetApis(apis map[string]*_ApiMap) {
+func resetAPIs(apis map[string]*_APIMap) {
apiLocker.Lock()
defer apiLocker.Unlock()
apiOfStrategy = apis
}
-func loadStategyApi() {
- apis, e := dao_strategy.GetAllStrategyApi()
+func loadStategyAPI() {
+ apis, e := dao_strategy.GetAllStrategyAPI()
if e != nil {
return
}
- tem := make(map[string]*_ApiMap)
+ tem := make(map[string]*_APIMap)
for _, api := range apis {
as, has := tem[api.StrategyID]
if !has {
- as = &_ApiMap{
- apis: make(map[int]*entity.StrategyApi),
+ as = &_APIMap{
+ apis: make(map[int]*entity.StrategyAPI),
}
}
- as.apis[api.ApiId] = api
+ as.apis[api.APIID] = api
tem[api.StrategyID] = as
}
- resetApis(tem)
+ resetAPIs(tem)
}
diff --git a/goku-node/manager/strategy-api-plugin-manager/strategy-api-plugin.go b/goku-node/manager/strategy-api-plugin-manager/strategy-api-plugin.go
index fb84d23..23ec1c7 100644
--- a/goku-node/manager/strategy-api-plugin-manager/strategy-api-plugin.go
+++ b/goku-node/manager/strategy-api-plugin-manager/strategy-api-plugin.go
@@ -1,4 +1,4 @@
-package strategy_api_plugin_manager
+package strategyapipluginmanager
import (
"fmt"
@@ -15,26 +15,28 @@ import (
)
func init() {
- updater.Add(loadStategyApiPlugin, 8, "goku_conn_plugin_strategy", "goku_conn_plugin_api", "goku_conn_strategy_api", "goku_gateway_strategy", "goku_gateway_api", "goku_plugin")
+ updater.Add(loadStategyAPIPlugin, 8, "goku_conn_plugin_strategy", "goku_conn_plugin_api", "goku_conn_strategy_api", "goku_gateway_strategy", "goku_gateway_api", "goku_plugin")
}
var (
- pluginsOfApi = make(map[string][]*entity.PluginHandlerExce)
+ pluginsOfAPI = make(map[string][]*entity.PluginHandlerExce)
locker sync.RWMutex
)
-func get(strategyId string, apiId int) ([]*entity.PluginHandlerExce, bool) {
+func get(strategyID string, apiID int) ([]*entity.PluginHandlerExce, bool) {
locker.RLock()
defer locker.RUnlock()
- key := strategyId + ":" + strconv.Itoa(apiId)
- p, has := pluginsOfApi[key]
+ key := strategyID + ":" + strconv.Itoa(apiID)
+ p, has := pluginsOfAPI[key]
return p, has
}
-func GetPluginsOfApi(strategyId string, apiId int) ([]*entity.PluginHandlerExce, bool) {
- p, has := get(strategyId, apiId)
+
+//GetPluginsOfAPI 获取接口插件
+func GetPluginsOfAPI(strategyID string, apiID int) ([]*entity.PluginHandlerExce, bool) {
+ p, has := get(strategyID, apiID)
if !has {
- return strategy_plugin_manager.GetPluginsOfStrategy(strategyId)
+ return strategy_plugin_manager.GetPluginsOfStrategy(strategyID)
}
return p, true
}
@@ -47,19 +49,19 @@ func reset(plugins map[string][]*entity.PluginHandlerExce) {
locker.Lock()
defer locker.Unlock()
- pluginsOfApi = plugins
+ pluginsOfAPI = plugins
}
-func loadStategyApiPlugin() {
- plugins, err := dao_strategy.GetApiPlugin()
+func loadStategyAPIPlugin() {
+ plugins, err := dao_strategy.GetAPIPlugin()
if err != nil {
return
}
phsa := make(map[string]map[int][]*entity.PluginHandlerExce)
for _, p := range plugins {
- apiId, _ := strconv.Atoi(p.ApiId)
+ apiID, _ := strconv.Atoi(p.APIId)
phs, has := phsa[p.StrategyID]
if !has {
@@ -72,7 +74,7 @@ func loadStategyApiPlugin() {
continue
}
- obj, err := handle.Factory.Create(p.PluginConfig, node_common.ClusterName(), p.UpdateTag, p.StrategyID, apiId)
+ obj, err := handle.Factory.Create(p.PluginConfig, nodecommon.ClusterName(), p.UpdateTag, p.StrategyID, apiID)
if err != nil {
continue
}
@@ -82,21 +84,21 @@ func loadStategyApiPlugin() {
Name: p.PluginName,
IsStop: handle.Info.IsStop,
}
- list, has := phsa[p.StrategyID][apiId]
+ list, has := phsa[p.StrategyID][apiID]
if !has {
list = make([]*entity.PluginHandlerExce, 0)
- phsa[p.StrategyID][apiId] = list
+ phsa[p.StrategyID][apiID] = list
}
- phsa[p.StrategyID][apiId] = append(list, handleExec)
+ phsa[p.StrategyID][apiID] = append(list, handleExec)
}
phl := make(map[string][]*entity.PluginHandlerExce)
- for strategyId, pla := range phsa {
- pls, ok := strategy_plugin_manager.GetPluginsOfStrategy(strategyId)
+ for strategyID, pla := range phsa {
+ pls, ok := strategy_plugin_manager.GetPluginsOfStrategy(strategyID)
- for apiId, list := range pla {
- key := fmt.Sprintf("%s:%d", strategyId, apiId)
+ for apiID, list := range pla {
+ key := fmt.Sprintf("%s:%d", strategyID, apiID)
if ok {
list = append(list, pls...)
diff --git a/goku-node/manager/strategy-manager/strategy.go b/goku-node/manager/strategy-manager/strategy.go
index 80b3872..7229bff 100644
--- a/goku-node/manager/strategy-manager/strategy.go
+++ b/goku-node/manager/strategy-manager/strategy.go
@@ -1,4 +1,4 @@
-package strategy_manager
+package strategymanager
import (
"sync"
@@ -13,7 +13,7 @@ func init() {
// loadStategy()
}
-//GetAnonymous: 获取匿名策略
+//GetAnonymous 获取匿名策略
//return: 开放策略ID,是否有效
func GetAnonymous() (*entity.Strategy, bool) {
if defStrategy == nil || defStrategy.EnableStatus != 1 {
@@ -22,17 +22,17 @@ func GetAnonymous() (*entity.Strategy, bool) {
return defStrategy, true
}
-//CheckStategy 测试策略Id是否生效
-func CheckStategy(stategyId string) bool {
+//CheckStategy 测试策略ID是否生效
+func CheckStategy(stategyID string) bool {
lockerStategy.RLock()
defer lockerStategy.RUnlock()
- _, has := strategys[stategyId]
+ _, has := strategys[stategyID]
return has
}
var (
- strategys = make(map[string]*entity.Strategy)
- defStrategy *entity.Strategy = nil
+ strategys = make(map[string]*entity.Strategy)
+ defStrategy *entity.Strategy
lockerStategy sync.RWMutex
)
@@ -43,6 +43,7 @@ func reset(s map[string]*entity.Strategy, def *entity.Strategy) {
defStrategy = def
}
+//Get get
func Get(id string) (*entity.Strategy, bool) {
lockerStategy.RLock()
defer lockerStategy.RUnlock()
@@ -50,6 +51,7 @@ func Get(id string) (*entity.Strategy, bool) {
return s, has
}
+//Has has
func Has(id string) bool {
lockerStategy.RLock()
defer lockerStategy.RUnlock()
diff --git a/goku-node/manager/strategy-plugin-manager/plugins.go b/goku-node/manager/strategy-plugin-manager/plugins.go
index d66ac2d..8a22dcf 100644
--- a/goku-node/manager/strategy-plugin-manager/plugins.go
+++ b/goku-node/manager/strategy-plugin-manager/plugins.go
@@ -1 +1 @@
-package strategy_plugin_manager
+package strategypluginmanager
diff --git a/goku-node/manager/strategy-plugin-manager/stategy-plugin.go b/goku-node/manager/strategy-plugin-manager/stategy-plugin.go
index 6263d00..ee2cb60 100644
--- a/goku-node/manager/strategy-plugin-manager/stategy-plugin.go
+++ b/goku-node/manager/strategy-plugin-manager/stategy-plugin.go
@@ -1,4 +1,4 @@
-package strategy_plugin_manager
+package strategypluginmanager
import (
"github.com/eolinker/goku-api-gateway/goku-node/node-common"
@@ -20,10 +20,11 @@ var (
locker sync.RWMutex
)
-func GetPluginsOfStrategy(strategyId string) ([]*entity.PluginHandlerExce, bool) {
+//GetPluginsOfStrategy 获取策略插件
+func GetPluginsOfStrategy(strategyID string) ([]*entity.PluginHandlerExce, bool) {
locker.RLock()
defer locker.RUnlock()
- p, has := pluginsOfStrategy[strategyId]
+ p, has := pluginsOfStrategy[strategyID]
if !has {
return nil, false
}
@@ -31,7 +32,6 @@ func GetPluginsOfStrategy(strategyId string) ([]*entity.PluginHandlerExce, bool)
}
func reset(plugins map[string][]*entity.PluginHandlerExce) {
- //def:=plugin_manager.GetDefaultPlugins()
for name := range plugins {
//plugins[name] = append(list,def...)
sort.Sort(sort.Reverse(entity.PluginSlice(plugins[name])))
@@ -57,7 +57,7 @@ func loadStategyPlugin() {
if handle == nil {
continue
}
- excer, err := handle.Factory.Create(p.PluginConfig, node_common.ClusterName(), p.UpdateTag, p.StrategyID, 0)
+ excer, err := handle.Factory.Create(p.PluginConfig, nodecommon.ClusterName(), p.UpdateTag, p.StrategyID, 0)
if err != nil {
continue
diff --git a/goku-node/manager/updater/update.go b/goku-node/manager/updater/update.go
index 0fd19b7..701e982 100644
--- a/goku-node/manager/updater/update.go
+++ b/goku-node/manager/updater/update.go
@@ -22,6 +22,7 @@ var (
handlerExecs = make([]*updateHandlerExec, 0)
)
+//UpdateHandleFunc update handle func
type UpdateHandleFunc func()
func init() {
@@ -41,6 +42,7 @@ func updatePeriod(period int) {
periodCh <- period
}
+//Add add
func Add(handler UpdateHandleFunc, priority int, tables ...string) {
sort.Strings(tables)
key := strings.Join(tables, ":")
@@ -64,10 +66,12 @@ func Add(handler UpdateHandleFunc, priority int, tables ...string) {
handlers[key] = hfs
}
+//Update update
func Update() {
ch <- true
}
+//InitUpdate init update
func InitUpdate() {
locker.Lock()
defer locker.Unlock()
@@ -130,8 +134,9 @@ func updates() {
}
}
+//CheckUpdate check update
func CheckUpdate(last time.Time, tables ...string) (bool, time.Time) {
- t, err := dao.GetLastUpdateOfApi(tables...)
+ t, err := dao.GetLastUpdateOfAPI(tables...)
if err != nil {
return false, last
}
diff --git a/goku-node/node-common/constant.go b/goku-node/node-common/constant.go
index 144260c..85fa1be 100644
--- a/goku-node/node-common/constant.go
+++ b/goku-node/node-common/constant.go
@@ -1,4 +1,4 @@
-package node_common
+package nodecommon
import (
"fmt"
@@ -6,24 +6,31 @@ import (
)
var (
+ //ListenPort 网关监听端口
ListenPort = 6689
clusterName string
- adminUrl = ""
+ adminURL = ""
)
+//SetClusterName 设置集群名称
func SetClusterName(name string) {
clusterName = name
}
+
+//ClusterName 获取集群名称
func ClusterName() string {
return clusterName
}
+//SetAdmin 设置admin地址
func SetAdmin(host string) {
h := strings.TrimPrefix(host, "http://")
h = strings.TrimSuffix(h, "/")
- adminUrl = fmt.Sprintf("http://%s", h)
+ adminURL = fmt.Sprintf("http://%s", h)
}
-func GetAdminUrl(path string) string {
+
+//GetAdminURL 获取adminURL
+func GetAdminURL(path string) string {
p := strings.TrimPrefix(path, "/")
- return fmt.Sprintf("%s/%s", adminUrl, p)
+ return fmt.Sprintf("%s/%s", adminURL, p)
}
diff --git a/goku-node/node-common/match.go b/goku-node/node-common/match.go
index d3d8b21..8471d06 100644
--- a/goku-node/node-common/match.go
+++ b/goku-node/node-common/match.go
@@ -1,15 +1,15 @@
-package node_common
+package nodecommon
import "strings"
-// 匹配restful参数
+//MatchRestful 匹配restful参数
func MatchRestful(requestURL string, params []string) string {
if len(params) == 0 {
return requestURL
}
// 将匹配URI中的query参数清除
requestURL = InterceptURL(requestURL, "?")
- var postfix bool = false
+ var postfix = false
// 将URI最后放的"/"去掉
if string(requestURL[len(requestURL)-1]) == "/" {
postfix = true
@@ -22,10 +22,10 @@ func MatchRestful(requestURL string, params []string) string {
if len(v) > 0 {
if string(v[0]) == ":" {
url += params[n] + "/"
- n += 1
+ n = n + 1
} else if string(v[0]) == "{" && string(v[len(v)-1]) == "}" {
url += params[n] + "/"
- n += 1
+ n = n + 1
} else {
url += v + "/"
}
@@ -33,12 +33,11 @@ func MatchRestful(requestURL string, params []string) string {
}
if !postfix {
return url[:len(url)-1]
- } else {
- return url
}
+ return url
}
-// 匹配URI
+//MatchURI 匹配URI
func MatchURI(requestPath string, matchURI string) (bool, string, []string) {
// 将匹配URI中的query参数清除
matchURI = InterceptURL(matchURI, "?")
@@ -46,7 +45,7 @@ func MatchURI(requestPath string, matchURI string) (bool, string, []string) {
if requestPath == matchURI {
return true, "", nil
}
- var postfix bool = false
+ var postfix = false
// 将URI最后的"/"去掉
if string(requestPath[len(requestPath)-1]) == "/" {
postfix = true
@@ -67,7 +66,7 @@ func MatchURI(requestPath string, matchURI string) (bool, string, []string) {
n := 0
param := make([]string, 0)
for i, v := range matchArray {
- n += 1
+ n = n + 1
if v == requestArray[i] {
continue
} else {
@@ -89,10 +88,11 @@ func MatchURI(requestPath string, matchURI string) (bool, string, []string) {
}
if !postfix {
return true, splitURL[:len(splitURL)-1], param
- } else {
- return true, splitURL, param
}
+ return true, splitURL, param
}
+
+//InterceptURL 过滤URL
func InterceptURL(str, substr string) string {
result := strings.Index(str, substr)
var rs string
@@ -104,7 +104,7 @@ func InterceptURL(str, substr string) string {
return rs
}
-// 过滤双斜杠
+//FilterSlash 过滤双斜杠
func FilterSlash(uri string) string {
replaceURI := strings.ReplaceAll(uri, "//", "/")
return replaceURI
diff --git a/goku-node/plugin-flow/access.go b/goku-node/plugin-flow/access.go
index 377dd4e..c439937 100644
--- a/goku-node/plugin-flow/access.go
+++ b/goku-node/plugin-flow/access.go
@@ -1,4 +1,4 @@
-package plugin_flow
+package pluginflow
import (
log "github.com/eolinker/goku-api-gateway/goku-log"
@@ -29,32 +29,32 @@ func getPluginNameByType(authType string) (string, bool) {
return name, has
}
-// 执行插件的Access函数
+//AccessFunc 执行插件的Access函数
func AccessFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (bool, int) {
- requestId := ctx.RequestId()
+ requestID := ctx.RequestId()
authType := ctx.Request().GetHeader("Authorization-Type")
authName, _ := getPluginNameByType(authType)
defer func(ctx *common.Context) {
- log.Debug(requestId, " access plugin default: begin")
+ log.Debug(requestID, " access plugin default: begin")
for _, handler := range plugin_manager.GetDefaultPlugins() {
if handler.PluginObj.Access == nil || reflect.ValueOf(handler.PluginObj.Access).IsNil() {
continue
}
ctx.SetPlugin(handler.Name)
- log.Info(requestId, " access plugin:", handler.Name)
+ log.Info(requestID, " access plugin:", handler.Name)
now := time.Now()
_, err := handler.PluginObj.Access.Access(ctx)
- log.Debug(requestId, " access plugin:", handler.Name, " Duration", time.Since(now))
+ log.Debug(requestID, " access plugin:", handler.Name, " Duration", time.Since(now))
if err != nil {
- log.Warn(requestId, " access plugin:", handler.Name, " error:", err.Error())
+ log.Warn(requestID, " access plugin:", handler.Name, " error:", err.Error())
}
}
- log.Debug(requestId, " access plugin default: end")
+ log.Debug(requestID, " access plugin default: end")
}(ctx)
isAuthSucess := false
isNeedAuth := false
- log.Debug(requestId, " access plugin auth check: begin")
+ log.Debug(requestID, " access plugin auth check: begin")
for _, handler := range handleFunc {
if _, has := authPluginNames[handler.Name]; has {
isNeedAuth = true
@@ -65,33 +65,33 @@ func AccessFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (bo
continue
}
ctx.SetPlugin(handler.Name)
- log.Debug(requestId, " access plugin:", handler.Name, " begin")
+ log.Debug(requestID, " access plugin:", handler.Name, " begin")
now := time.Now()
flag, err := handler.PluginObj.Access.Access(ctx)
- log.Debug(requestId, " access plugin:", handler.Name, " Duration", time.Since(now))
+ log.Debug(requestID, " access plugin:", handler.Name, " Duration", time.Since(now))
if flag == false {
// 校验失败
if err != nil {
- log.Warn(requestId, " access auth:[", handler.Name, "] error:", err.Error())
+ log.Warn(requestID, " access auth:[", handler.Name, "] error:", err.Error())
}
- log.Info(requestId, " auth [", authName, "] refuse")
+ log.Info(requestID, " auth [", authName, "] refuse")
return false, 0
}
- log.Debug(requestId, " auth [", authName, "] pass")
+ log.Debug(requestID, " auth [", authName, "] pass")
isAuthSucess = true
}
}
- log.Debug(requestId, " access plugin auth check: end")
+ log.Debug(requestID, " access plugin auth check: end")
// 需要校验但是没有执行校验
if isNeedAuth && !isAuthSucess {
- log.Warn(requestId, " Illegal authorization type:", authType)
+ log.Warn(requestID, " Illegal authorization type:", authType)
ctx.SetStatus(403, "403")
ctx.SetBody([]byte("[ERROR]Illegal authorization type!"))
return false, 0
}
lastIndex := 0
- log.Debug(requestId, " access plugin : begin")
+ log.Debug(requestID, " access plugin : begin")
// 执行校验以外的插件
for index, handler := range handleFunc {
lastIndex = index
@@ -104,19 +104,19 @@ func AccessFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (bo
}
ctx.SetPlugin(handler.Name)
- log.Debug(requestId, " access plugin:", handler.Name)
+ log.Debug(requestID, " access plugin:", handler.Name)
now := time.Now()
flag, err := handler.PluginObj.Access.Access(ctx)
- log.Debug(requestId, " access plugin:", handler.Name, " Duration:", time.Since(now))
+ log.Debug(requestID, " access plugin:", handler.Name, " Duration:", time.Since(now))
if err != nil {
- log.Warn(requestId, " access plugin:", handler.Name, " error:", err.Error())
+ log.Warn(requestID, " access plugin:", handler.Name, " error:", err.Error())
}
if flag == false && handler.IsStop {
- log.Info(requestId, " access plugin:", handler.Name, " stop")
+ log.Info(requestID, " access plugin:", handler.Name, " stop")
return false, index
}
- log.Debug(requestId, " access plugin:", handler.Name, " continue")
+ log.Debug(requestID, " access plugin:", handler.Name, " continue")
}
- log.Debug(requestId, " access plugin : end")
+ log.Debug(requestID, " access plugin : end")
return true, lastIndex
}
diff --git a/goku-node/plugin-flow/before.go b/goku-node/plugin-flow/before.go
index eeb9713..3cc29ac 100644
--- a/goku-node/plugin-flow/before.go
+++ b/goku-node/plugin-flow/before.go
@@ -1,4 +1,4 @@
-package plugin_flow
+package pluginflow
import (
log "github.com/eolinker/goku-api-gateway/goku-log"
@@ -8,28 +8,28 @@ import (
"time"
)
-// 执行插件的BeforeMatch函数
+//BeforeMatch 执行插件的BeforeMatch函数
func BeforeMatch(ctx *common.Context) bool {
- requestId := ctx.RequestId()
+ requestID := ctx.RequestId()
defer func(ctx *common.Context) {
- log.Debug(requestId, " before plugin default: begin")
+ log.Debug(requestID, " before plugin default: begin")
for _, handler := range plugin_manager.GetDefaultPlugins() {
if handler.PluginObj.BeforeMatch == nil || reflect.ValueOf(handler.PluginObj.BeforeMatch).IsNil() {
continue
}
ctx.SetPlugin(handler.Name)
- log.Debug(requestId, " before plugin :", handler.Name, " start")
+ log.Debug(requestID, " before plugin :", handler.Name, " start")
now := time.Now()
_, err := handler.PluginObj.BeforeMatch.BeforeMatch(ctx)
- log.Debug(requestId, " before plugin :", handler.Name, " Duration:", time.Since(now))
- log.Debug(requestId, " before plugin :", handler.Name, " end")
+ log.Debug(requestID, " before plugin :", handler.Name, " Duration:", time.Since(now))
+ log.Debug(requestID, " before plugin :", handler.Name, " end")
if err != nil {
- log.Warn(requestId, " before plugin:", handler.Name, " error:", err.Error())
+ log.Warn(requestID, " before plugin:", handler.Name, " error:", err.Error())
}
}
- log.Debug(requestId, " before plugin default: end")
+ log.Debug(requestID, " before plugin default: end")
}(ctx)
- log.Debug(requestId, " before plugin : begin")
+ log.Debug(requestID, " before plugin : begin")
for _, handler := range plugin_manager.GetBeforPlugins() {
if handler.PluginObj.BeforeMatch == nil || reflect.ValueOf(handler.PluginObj.BeforeMatch).IsNil() {
@@ -37,14 +37,14 @@ func BeforeMatch(ctx *common.Context) bool {
}
ctx.SetPlugin(handler.Name)
- log.Debug(requestId, " before plugin :", handler.Name, " start")
+ log.Debug(requestID, " before plugin :", handler.Name, " start")
now := time.Now()
flag, err := handler.PluginObj.BeforeMatch.BeforeMatch(ctx)
- log.Debug(requestId, " before plugin :", handler.Name, " Duration:", time.Since(now))
- log.Debug(requestId, " before plugin :", handler.Name, " end")
+ log.Debug(requestID, " before plugin :", handler.Name, " Duration:", time.Since(now))
+ log.Debug(requestID, " before plugin :", handler.Name, " end")
if err != nil {
- log.Warn(requestId, " before plugin:", handler.Name, " error:", err.Error())
+ log.Warn(requestID, " before plugin:", handler.Name, " error:", err.Error())
}
if flag == false {
if handler.IsStop == true {
@@ -52,6 +52,6 @@ func BeforeMatch(ctx *common.Context) bool {
}
}
}
- log.Debug(requestId, " before plugin : end")
+ log.Debug(requestID, " before plugin : end")
return true
}
diff --git a/goku-node/plugin-flow/proxy.go b/goku-node/plugin-flow/proxy.go
index 0de3a0f..d975c2c 100644
--- a/goku-node/plugin-flow/proxy.go
+++ b/goku-node/plugin-flow/proxy.go
@@ -1,4 +1,4 @@
-package plugin_flow
+package pluginflow
import (
log "github.com/eolinker/goku-api-gateway/goku-log"
@@ -10,30 +10,30 @@ import (
"time"
)
-// 执行插件的Proxy函数
+//ProxyFunc 执行插件的Proxy函数
func ProxyFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (bool, int) {
- requestId := ctx.RequestId()
+ requestID := ctx.RequestId()
defer func(ctx *common.Context) {
- log.Debug(requestId, " Proxy plugin default: begin")
+ log.Debug(requestID, " Proxy plugin default: begin")
for _, handler := range plugin_manager.GetDefaultPlugins() {
if handler.PluginObj.Proxy == nil || reflect.ValueOf(handler.PluginObj.Proxy).IsNil() {
continue
}
ctx.SetPlugin(handler.Name)
- log.Debug(requestId, " Proxy plugin :", handler.Name, " start")
+ log.Debug(requestID, " Proxy plugin :", handler.Name, " start")
now := time.Now()
_, err := handler.PluginObj.Proxy.Proxy(ctx)
- log.Debug(requestId, " Proxy plugin :", handler.Name, " Duration:", time.Since(now))
- log.Debug(requestId, " Proxy plugin :", handler.Name, " end")
+ log.Debug(requestID, " Proxy plugin :", handler.Name, " Duration:", time.Since(now))
+ log.Debug(requestID, " Proxy plugin :", handler.Name, " end")
if err != nil {
- log.Warn(requestId, " Proxy plugin:", handler.Name, " error:", err.Error())
+ log.Warn(requestID, " Proxy plugin:", handler.Name, " error:", err.Error())
}
}
- log.Debug(requestId, " Proxy plugin default: begin")
+ log.Debug(requestID, " Proxy plugin default: begin")
}(ctx)
lastIndex := 0
- log.Debug(requestId, " Proxy plugin : begin")
+ log.Debug(requestID, " Proxy plugin : begin")
for index, handler := range handleFunc {
lastIndex = index
if handler.PluginObj.Proxy == nil || reflect.ValueOf(handler.PluginObj.Proxy).IsNil() {
@@ -41,20 +41,20 @@ func ProxyFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (boo
}
ctx.SetPlugin(handler.Name)
- log.Debug(requestId, " Proxy plugin :", handler.Name, " start")
+ log.Debug(requestID, " Proxy plugin :", handler.Name, " start")
now := time.Now()
flag, err := handler.PluginObj.Proxy.Proxy(ctx)
- log.Debug(requestId, " Proxy plugin :", handler.Name, " Duration:", time.Since(now))
- log.Debug(requestId, " Proxy plugin :", handler.Name, " end")
+ log.Debug(requestID, " Proxy plugin :", handler.Name, " Duration:", time.Since(now))
+ log.Debug(requestID, " Proxy plugin :", handler.Name, " end")
if err != nil {
- log.Warn(requestId, " Proxy plugin :", handler.Name, " error: ", err.Error())
+ log.Warn(requestID, " Proxy plugin :", handler.Name, " error: ", err.Error())
}
if flag == false && handler.IsStop == true {
return false, lastIndex
}
}
- log.Debug(requestId, " Proxy plugin : end")
+ log.Debug(requestID, " Proxy plugin : end")
return true, lastIndex
}
diff --git a/goku-node/queue/queue.go b/goku-node/queue/queue.go
deleted file mode 100644
index 651039c..0000000
--- a/goku-node/queue/queue.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package queue
-
-type GokuQueue interface {
- Size() int //大小
- Front() interface{} //第一个元素
- End() interface{} //最后一个元素
- IsEmpty() bool //是否为空
- Enqueue(data interface{}) //入队
- Dequeue() interface{} //出对
- Clear() //清空
-}
-
-type Queue struct {
- datastore []interface{}
- theSize int
-}
-
-func (goku_queue *Queue) Clear() {
- goku_queue.datastore = make([]interface{}, 0) //开辟内存
- goku_queue.theSize = 0
-}
-
-func NewQueue() *Queue {
- goku_queue := new(Queue)
- goku_queue.Clear()
- return goku_queue
-
-}
-
-func (goku_queue *Queue) Size() int {
- return goku_queue.theSize //大小
-}
-
-func (goku_queue *Queue) Front() interface{} {
- if goku_queue.Size() == 0 { //判断是否为空
- return nil
- }
- return goku_queue.datastore[0]
-}
-
-func (goku_queue *Queue) End() interface{} {
- if goku_queue.Size() == 0 { //判断是否为空
- return nil
- }
- return goku_queue.datastore[goku_queue.theSize-1]
-}
-
-func (goku_queue *Queue) IsEmpty() bool {
- return goku_queue.theSize == 0
-}
-
-func (goku_queue *Queue) Enqueue(data interface{}) {
- goku_queue.datastore = append(goku_queue.datastore, data) //入队
- goku_queue.theSize = goku_queue.theSize + 1
-}
-
-func (goku_queue *Queue) Dequeue() interface{} {
- size := len(goku_queue.datastore)
- if size < 1 { //判断是否为空
- return nil
- }
- datastore := make([]interface{}, 0)
- data := goku_queue.datastore[0]
- if goku_queue.theSize > 1 {
- datastore = goku_queue.datastore[1:] //截取
- }
- goku_queue.datastore = datastore
- goku_queue.theSize = goku_queue.theSize - 1
- return data
-}
diff --git a/goku-node/redis-plugin-proxy/pipeline.go b/goku-node/redis-plugin-proxy/pipeline.go
index 70bf307..21fa5ac 100644
--- a/goku-node/redis-plugin-proxy/pipeline.go
+++ b/goku-node/redis-plugin-proxy/pipeline.go
@@ -1,48 +1,58 @@
-package redis_plugin_proxy
+package redispluginproxy
import (
"github.com/eolinker/goku-plugin"
"github.com/go-redis/redis"
)
+//PipelineProxy pipelineProxy
type PipelineProxy struct {
RedisProxy
pipeliner redis.Pipeliner
}
+//Auth auth
func (p *PipelineProxy) Auth(password string) goku_plugin.StatusCmd {
return p.pipeliner.Auth(password)
}
+//Select select
func (p *PipelineProxy) Select(index int) goku_plugin.StatusCmd {
return p.pipeliner.Select(index)
}
+//SwapDB swapDB
func (p *PipelineProxy) SwapDB(index1, index2 int) goku_plugin.StatusCmd {
return p.pipeliner.SwapDB(index1, index2)
}
+//ClientSetName clientSetName
func (p *PipelineProxy) ClientSetName(name string) goku_plugin.BoolCmd {
return p.pipeliner.ClientSetName(name)
}
+//Do do
func (p *PipelineProxy) Do(args ...interface{}) goku_plugin.Cmd {
return p.pipeliner.Do(args...)
}
+//Process process
func (p *PipelineProxy) Process(cmd goku_plugin.Cmder) error {
arg := cmd.Args()
return p.pipeliner.Process(redis.NewCmd(arg...))
}
+//Close close
func (p *PipelineProxy) Close() error {
return p.pipeliner.Close()
}
+//Discard discard
func (p *PipelineProxy) Discard() error {
return p.pipeliner.Discard()
}
+//Exec exec
func (p *PipelineProxy) Exec() ([]goku_plugin.Cmder, error) {
cmders, err := p.pipeliner.Exec()
diff --git a/goku-node/redis-plugin-proxy/proxy.go b/goku-node/redis-plugin-proxy/proxy.go
index 691127b..9697f8b 100644
--- a/goku-node/redis-plugin-proxy/proxy.go
+++ b/goku-node/redis-plugin-proxy/proxy.go
@@ -1,4 +1,4 @@
-package redis_plugin_proxy
+package redispluginproxy
import (
redis2 "github.com/eolinker/goku-plugin"
@@ -6,300 +6,388 @@ import (
"time"
)
+//RedisProxy redisProxy
type RedisProxy struct {
redisClient redis.Cmdable
}
+//Ping ping
func (p *RedisProxy) Ping() redis2.StatusCmd { return p.redisClient.Ping() }
+//Del del
func (p *RedisProxy) Del(keys ...string) redis2.IntCmd { return p.redisClient.Del(keys...) }
+//Unlink unlink
func (p *RedisProxy) Unlink(keys ...string) redis2.IntCmd { return p.redisClient.Unlink(keys...) }
+//Dump dump
func (p *RedisProxy) Dump(key string) redis2.StringCmd { return p.redisClient.Dump(key) }
+//Exists exists
func (p *RedisProxy) Exists(keys ...string) redis2.IntCmd { return p.redisClient.Exists(keys...) }
+//Expire expire
func (p *RedisProxy) Expire(key string, expiration time.Duration) redis2.BoolCmd {
return p.redisClient.Expire(key, expiration)
}
+//ExpireAt expireAt
func (p *RedisProxy) ExpireAt(key string, tm time.Time) redis2.BoolCmd {
return p.redisClient.ExpireAt(key, tm)
}
+//Keys keys
func (p *RedisProxy) Keys(pattern string) redis2.StringSliceCmd { return p.redisClient.Keys(pattern) }
+//RandomKey randomKey
func (p *RedisProxy) RandomKey() redis2.StringCmd { return p.redisClient.RandomKey() }
+//Rename rename
func (p *RedisProxy) Rename(key, newkey string) redis2.StatusCmd {
return p.redisClient.Rename(key, newkey)
}
+//RenameNX renameNx
func (p *RedisProxy) RenameNX(key, newkey string) redis2.BoolCmd {
return p.redisClient.RenameNX(key, newkey)
}
+//Restore restore
func (p *RedisProxy) Restore(key string, ttl time.Duration, value string) redis2.StatusCmd {
return p.redisClient.Restore(key, ttl, value)
}
+//RestoreReplace restore replace
func (p *RedisProxy) RestoreReplace(key string, ttl time.Duration, value string) redis2.StatusCmd {
return p.redisClient.RestoreReplace(key, ttl, value)
}
+//Append append
func (p *RedisProxy) Append(key, value string) redis2.IntCmd { return p.redisClient.Append(key, value) }
//func (p *RedisProxy) BitCountS(key string, Start, End int64) redis2.IntCmd { return p.redisClient.BitCountS(key,Start,End)}
+//BitOpAnd bitOpAnd
func (p *RedisProxy) BitOpAnd(destKey string, keys ...string) redis2.IntCmd {
- return p.redisClient.BitOpAnd(destKey, keys ...)
+ return p.redisClient.BitOpAnd(destKey, keys...)
}
+//BitOpOr bitOpOr
func (p *RedisProxy) BitOpOr(destKey string, keys ...string) redis2.IntCmd {
- return p.redisClient.BitOpOr(destKey, keys ...)
+ return p.redisClient.BitOpOr(destKey, keys...)
}
+//BitOpXor bitOpXor
func (p *RedisProxy) BitOpXor(destKey string, keys ...string) redis2.IntCmd {
- return p.redisClient.BitOpXor(destKey, keys ...)
+ return p.redisClient.BitOpXor(destKey, keys...)
}
+//BitOpNot bitOpNot
func (p *RedisProxy) BitOpNot(destKey string, key string) redis2.IntCmd {
return p.redisClient.BitOpNot(destKey, key)
}
+//BitPos bitPos
func (p *RedisProxy) BitPos(key string, bit int64, pos ...int64) redis2.IntCmd {
- return p.redisClient.BitPos(key, bit, pos ...)
+ return p.redisClient.BitPos(key, bit, pos...)
}
+//Decr decr
func (p *RedisProxy) Decr(key string) redis2.IntCmd { return p.redisClient.Decr(key) }
+//DecrBy decrBy
func (p *RedisProxy) DecrBy(key string, decrement int64) redis2.IntCmd {
return p.redisClient.DecrBy(key, decrement)
}
+//Get get
func (p *RedisProxy) Get(key string) redis2.StringCmd { return p.redisClient.Get(key) }
+//GetBit getBit
func (p *RedisProxy) GetBit(key string, offset int64) redis2.IntCmd {
return p.redisClient.GetBit(key, offset)
}
+//GetRange getRange
func (p *RedisProxy) GetRange(key string, start, end int64) redis2.StringCmd {
return p.redisClient.GetRange(key, start, end)
}
+//GetSet getSet
func (p *RedisProxy) GetSet(key string, value interface{}) redis2.StringCmd {
return p.redisClient.GetSet(key, value)
}
+//Incr incr
func (p *RedisProxy) Incr(key string) redis2.IntCmd { return p.redisClient.Incr(key) }
+//IncrBy incrBy
func (p *RedisProxy) IncrBy(key string, value int64) redis2.IntCmd {
return p.redisClient.IncrBy(key, value)
}
+//IncrByFloat incrByFloat
func (p *RedisProxy) IncrByFloat(key string, value float64) redis2.FloatCmd {
return p.redisClient.IncrByFloat(key, value)
}
+//MGet mget
func (p *RedisProxy) MGet(keys ...string) redis2.SliceCmd { return p.redisClient.MGet(keys...) }
+//MSet mset
func (p *RedisProxy) MSet(pairs ...interface{}) redis2.StatusCmd { return p.redisClient.MSet(pairs) }
+//MSetNX msetnx
func (p *RedisProxy) MSetNX(pairs ...interface{}) redis2.BoolCmd { return p.redisClient.MSetNX(pairs) }
+//Set set
func (p *RedisProxy) Set(key string, value interface{}, expiration time.Duration) redis2.StatusCmd {
return p.redisClient.Set(key, value, expiration)
}
+//SetBit setbit
func (p *RedisProxy) SetBit(key string, offset int64, value int) redis2.IntCmd {
return p.redisClient.SetBit(key, offset, value)
}
+//SetNX setnx
func (p *RedisProxy) SetNX(key string, value interface{}, expiration time.Duration) redis2.BoolCmd {
return p.redisClient.SetNX(key, value, expiration)
}
+//SetXX setxx
func (p *RedisProxy) SetXX(key string, value interface{}, expiration time.Duration) redis2.BoolCmd {
return p.redisClient.SetXX(key, value, expiration)
}
+//SetRange setRange
func (p *RedisProxy) SetRange(key string, offset int64, value string) redis2.IntCmd {
return p.redisClient.SetRange(key, offset, value)
}
+//StrLen strLen
func (p *RedisProxy) StrLen(key string) redis2.IntCmd { return p.redisClient.StrLen(key) }
+//HDel hDel
func (p *RedisProxy) HDel(key string, fields ...string) redis2.IntCmd {
- return p.redisClient.HDel(key, fields ...)
+ return p.redisClient.HDel(key, fields...)
}
+//HExists hExists
func (p *RedisProxy) HExists(key, field string) redis2.BoolCmd {
return p.redisClient.HExists(key, field)
}
+//HGet hGet
func (p *RedisProxy) HGet(key, field string) redis2.StringCmd { return p.redisClient.HGet(key, field) }
+//HGetAll hGetAll
func (p *RedisProxy) HGetAll(key string) redis2.StringStringMapCmd { return p.redisClient.HGetAll(key) }
+//HIncrBy hIncrBy
func (p *RedisProxy) HIncrBy(key, field string, incr int64) redis2.IntCmd {
return p.redisClient.HIncrBy(key, field, incr)
}
+//HIncrByFloat hIncrByFloat
func (p *RedisProxy) HIncrByFloat(key, field string, incr float64) redis2.FloatCmd {
return p.redisClient.HIncrByFloat(key, field, incr)
}
+//HKeys hKeys
func (p *RedisProxy) HKeys(key string) redis2.StringSliceCmd { return p.redisClient.HKeys(key) }
+//HLen hLen
func (p *RedisProxy) HLen(key string) redis2.IntCmd { return p.redisClient.HLen(key) }
+//HMGet hMget
func (p *RedisProxy) HMGet(key string, fields ...string) redis2.SliceCmd {
- return p.redisClient.HMGet(key, fields ...)
+ return p.redisClient.HMGet(key, fields...)
}
+//HMSet hMset
func (p *RedisProxy) HMSet(key string, fields map[string]interface{}) redis2.StatusCmd {
return p.redisClient.HMSet(key, fields)
}
+//HSet hSet
func (p *RedisProxy) HSet(key, field string, value interface{}) redis2.BoolCmd {
return p.redisClient.HSet(key, field, value)
}
+//HSetNX hSetNx
func (p *RedisProxy) HSetNX(key, field string, value interface{}) redis2.BoolCmd {
return p.redisClient.HSetNX(key, field, value)
}
+//HVals hVals
func (p *RedisProxy) HVals(key string) redis2.StringSliceCmd { return p.redisClient.HVals(key) }
+//BLPop bLpop
func (p *RedisProxy) BLPop(timeout time.Duration, keys ...string) redis2.StringSliceCmd {
- return p.redisClient.BLPop(timeout, keys ...)
+ return p.redisClient.BLPop(timeout, keys...)
}
+//BRPop brpop
func (p *RedisProxy) BRPop(timeout time.Duration, keys ...string) redis2.StringSliceCmd {
- return p.redisClient.BRPop(timeout, keys ...)
+ return p.redisClient.BRPop(timeout, keys...)
}
+//BRPopLPush brPopLpush
func (p *RedisProxy) BRPopLPush(source, destination string, timeout time.Duration) redis2.StringCmd {
return p.redisClient.BRPopLPush(source, destination, timeout)
}
+//LIndex lIndex
func (p *RedisProxy) LIndex(key string, index int64) redis2.StringCmd {
return p.redisClient.LIndex(key, index)
}
+//LInsert lInsert
func (p *RedisProxy) LInsert(key, op string, pivot, value interface{}) redis2.IntCmd {
return p.redisClient.LInsert(key, op, pivot, value)
}
+//LInsertBefore lInsertBefore
func (p *RedisProxy) LInsertBefore(key string, pivot, value interface{}) redis2.IntCmd {
return p.redisClient.LInsertBefore(key, pivot, value)
}
+//LInsertAfter lInsertAfter
func (p *RedisProxy) LInsertAfter(key string, pivot, value interface{}) redis2.IntCmd {
return p.redisClient.LInsertAfter(key, pivot, value)
}
+//LLen llen
func (p *RedisProxy) LLen(key string) redis2.IntCmd { return p.redisClient.LLen(key) }
+//LPop lpop
func (p *RedisProxy) LPop(key string) redis2.StringCmd { return p.redisClient.LPop(key) }
+//LPush lPush
func (p *RedisProxy) LPush(key string, values ...interface{}) redis2.IntCmd {
- return p.redisClient.LPush(key, values ...)
+ return p.redisClient.LPush(key, values...)
}
+//LPushX lPushX
func (p *RedisProxy) LPushX(key string, value interface{}) redis2.IntCmd {
return p.redisClient.LPushX(key, value)
}
+//LRange lRange
func (p *RedisProxy) LRange(key string, start, stop int64) redis2.StringSliceCmd {
return p.redisClient.LRange(key, start, stop)
}
+//LRem lRem
func (p *RedisProxy) LRem(key string, count int64, value interface{}) redis2.IntCmd {
return p.redisClient.LRem(key, count, value)
}
+//LSet lSet
func (p *RedisProxy) LSet(key string, index int64, value interface{}) redis2.StatusCmd {
return p.redisClient.LSet(key, index, value)
}
+//LTrim lTrim
func (p *RedisProxy) LTrim(key string, start, stop int64) redis2.StatusCmd {
return p.redisClient.LTrim(key, start, stop)
}
+//RPop rPop
func (p *RedisProxy) RPop(key string) redis2.StringCmd { return p.redisClient.RPop(key) }
+//RPopLPush rPopLpush
func (p *RedisProxy) RPopLPush(source, destination string) redis2.StringCmd {
return p.redisClient.RPopLPush(source, destination)
}
+//RPush rPush
func (p *RedisProxy) RPush(key string, values ...interface{}) redis2.IntCmd {
- return p.redisClient.RPush(key, values ...)
+ return p.redisClient.RPush(key, values...)
}
+//RPushX rPushX
func (p *RedisProxy) RPushX(key string, value interface{}) redis2.IntCmd {
return p.redisClient.RPushX(key, value)
}
+//SAdd sAdd
func (p *RedisProxy) SAdd(key string, members ...interface{}) redis2.IntCmd {
- return p.redisClient.SAdd(key, members ...)
+ return p.redisClient.SAdd(key, members...)
}
+//SCard sCard
func (p *RedisProxy) SCard(key string) redis2.IntCmd { return p.redisClient.SCard(key) }
+//SDiff sDiff
func (p *RedisProxy) SDiff(keys ...string) redis2.StringSliceCmd { return p.redisClient.SDiff(keys...) }
+//SDiffStore sDiffStore
func (p *RedisProxy) SDiffStore(destination string, keys ...string) redis2.IntCmd {
- return p.redisClient.SDiffStore(destination, keys ...)
+ return p.redisClient.SDiffStore(destination, keys...)
}
+//SInter sInter
func (p *RedisProxy) SInter(keys ...string) redis2.StringSliceCmd {
return p.redisClient.SInter(keys...)
}
+//SInterStore sInterStore
func (p *RedisProxy) SInterStore(destination string, keys ...string) redis2.IntCmd {
- return p.redisClient.SInterStore(destination, keys ...)
+ return p.redisClient.SInterStore(destination, keys...)
}
+//SIsMember sIsMember
func (p *RedisProxy) SIsMember(key string, member interface{}) redis2.BoolCmd {
return p.redisClient.SIsMember(key, member)
}
+//SMembers sMembers
func (p *RedisProxy) SMembers(key string) redis2.StringSliceCmd { return p.redisClient.SMembers(key) }
+//SMembersMap sMembersMap
func (p *RedisProxy) SMembersMap(key string) redis2.StringStructMapCmd {
return p.redisClient.SMembersMap(key)
}
+//SMove sMove
func (p *RedisProxy) SMove(source, destination string, member interface{}) redis2.BoolCmd {
return p.redisClient.SMove(source, destination, member)
}
+//SPop sPop
func (p *RedisProxy) SPop(key string) redis2.StringCmd { return p.redisClient.SPop(key) }
+//SPopN sPopN
func (p *RedisProxy) SPopN(key string, count int64) redis2.StringSliceCmd {
return p.redisClient.SPopN(key, count)
}
+//SRandMember sRandMember
func (p *RedisProxy) SRandMember(key string) redis2.StringCmd { return p.redisClient.SRandMember(key) }
+//SRandMemberN sRandMemberN
func (p *RedisProxy) SRandMemberN(key string, count int64) redis2.StringSliceCmd {
return p.redisClient.SRandMemberN(key, count)
}
+//SRem sRem
func (p *RedisProxy) SRem(key string, members ...interface{}) redis2.IntCmd {
- return p.redisClient.SRem(key, members ...)
+ return p.redisClient.SRem(key, members...)
}
+//SUnion sUnion
func (p *RedisProxy) SUnion(keys ...string) redis2.StringSliceCmd {
return p.redisClient.SUnion(keys...)
}
+//SUnionStore sUnionStore
func (p *RedisProxy) SUnionStore(destination string, keys ...string) redis2.IntCmd {
- return p.redisClient.SUnionStore(destination, keys ...)
+ return p.redisClient.SUnionStore(destination, keys...)
}
+//Pipeline pipeLine
func (p *RedisProxy) Pipeline() redis2.Pipeliner {
pipe := p.redisClient.Pipeline()
return &PipelineProxy{
@@ -309,6 +397,7 @@ func (p *RedisProxy) Pipeline() redis2.Pipeliner {
}
+//Pipelined pipeLined
func (p *RedisProxy) Pipelined(fn func(redis2.Pipeliner) error) ([]redis2.Cmder, error) {
cmders, e := p.redisClient.Pipelined(func(pipeliner redis.Pipeliner) error {
pip := &PipelineProxy{
diff --git a/goku-node/redis-plugin-proxy/redis.go b/goku-node/redis-plugin-proxy/redis.go
index bf72f53..597f0e1 100644
--- a/goku-node/redis-plugin-proxy/redis.go
+++ b/goku-node/redis-plugin-proxy/redis.go
@@ -1,10 +1,11 @@
-package redis_plugin_proxy
+package redispluginproxy
import (
+ redis_manager "github.com/eolinker/goku-api-gateway/common/redis-manager"
"github.com/eolinker/goku-plugin"
- "github.com/eolinker/goku-api-gateway/common/redis-manager"
)
+//Create 创建redisManager
func Create() goku_plugin.RedisManager {
return &RedisManager{
@@ -15,14 +16,17 @@ func Create() goku_plugin.RedisManager {
}
+//RedisManager redisManager
type RedisManager struct {
def goku_plugin.Redis
}
+//Default default
func (m *RedisManager) Default() goku_plugin.Redis {
return m.def
}
+//Get get
func (m *RedisManager) Get(name string) (redis goku_plugin.Redis, has bool) {
panic("not implement")
}
diff --git a/goku-node/request/request.go b/goku-node/request/request.go
index 337ebfb..a33cf08 100644
--- a/goku-node/request/request.go
+++ b/goku-node/request/request.go
@@ -10,8 +10,9 @@ import (
"time"
)
-var Version string = "2.0"
+const requestVersion = "2.0"
+//Request request
type Request struct {
client *http.Client
method string
@@ -24,7 +25,7 @@ type Request struct {
timeout int
}
-// 创建新请求
+//NewRequest 创建新请求
func NewRequest(method string, URL *url.URL) (*Request, error) {
if method != "GET" && method != "POST" && method != "PUT" && method != "DELETE" &&
method != "HEAD" && method != "OPTIONS" && method != "PATCH" {
@@ -51,58 +52,58 @@ func newRequest(method string, URL *url.URL) (*Request, error) {
return r, nil
}
-// 设置请求头
-func (this *Request) SetHeader(key string, values ...string) {
+//SetHeader 设置请求头
+func (rq *Request) SetHeader(key string, values ...string) {
if len(values) > 0 {
- this.headers[key] = values[:]
+ rq.headers[key] = values[:]
} else {
- delete(this.headers, key)
+ delete(rq.headers, key)
}
}
-// 获取请求头
-func (this *Request) Headers() map[string][]string {
+//Headers 获取请求头
+func (rq *Request) Headers() map[string][]string {
headers := make(map[string][]string)
- for key, values := range this.headers {
+ for key, values := range rq.headers {
headers[key] = values[:]
}
return headers
}
-// 设置Query参数
-func (this *Request) SetQueryParam(key string, values ...string) {
+//SetQueryParam 设置Query参数
+func (rq *Request) SetQueryParam(key string, values ...string) {
if len(values) > 0 {
- this.queryParams[key] = values[:]
+ rq.queryParams[key] = values[:]
} else {
- delete(this.queryParams, key)
+ delete(rq.queryParams, key)
}
}
-// 设置请求超时时间
-func (this *Request) SetTimeout(timeout int) {
- this.timeout = timeout
+//SetTimeout 设置请求超时时间
+func (rq *Request) SetTimeout(timeout int) {
+ rq.timeout = timeout
}
-// 获取请求超时时间
-func (this *Request) GetTimeout() int {
- return this.timeout
+//GetTimeout 获取请求超时时间
+func (rq *Request) GetTimeout() int {
+ return rq.timeout
}
-// 发送请求
-func (this *Request) Send() (*http.Response, error) {
+//Send 发送请求
+func (rq *Request) Send() (*http.Response, error) {
// now := time.Now()
- req, err := this.parseBody()
+ req, err := rq.parseBody()
// fmt.Println("Parse body",time.Since(now))
if err != nil {
return nil, err
}
req.Header.Set("Accept-Encoding", "gzip")
// now = time.Now()
- req.Header = parseHeaders(this.headers)
+ req.Header = parseHeaders(rq.headers)
- this.client.Timeout = time.Duration(this.timeout) * time.Millisecond
+ rq.client.Timeout = time.Duration(rq.timeout) * time.Millisecond
- httpResponse, err := this.client.Do(req)
+ httpResponse, err := rq.client.Do(req)
if err != nil {
return nil, err
@@ -111,32 +112,31 @@ func (this *Request) Send() (*http.Response, error) {
}
-// 获取query参数
-func (this *Request) QueryParams() map[string][]string {
+//QueryParams 获取query参数
+func (rq *Request) QueryParams() map[string][]string {
params := make(map[string][]string)
- for key, values := range this.queryParams {
+ for key, values := range rq.queryParams {
params[key] = values[:]
}
return params
}
-// 获取完整的URL路径
-func (this *Request) UrlPath() string {
- if len(this.queryParams) > 0 {
- return this.URL + "?" + parseParams(this.queryParams).Encode()
- } else {
- return this.URL
+//URLPath 获取完整的URL路径
+func (rq *Request) URLPath() string {
+ if len(rq.queryParams) > 0 {
+ return rq.URL + "?" + parseParams(rq.queryParams).Encode()
}
+ return rq.URL
}
-// 设置URL
-func (this *Request) SetURL(url string) {
- this.URL = url
+//SetURL 设置URL
+func (rq *Request) SetURL(url string) {
+ rq.URL = url
}
-// 设置源数据
-func (this *Request) SetRawBody(body []byte) {
- this.body = body
+//SetRawBody 设置源数据
+func (rq *Request) SetRawBody(body []byte) {
+ rq.body = body
}
// 解析请求头
@@ -154,42 +154,42 @@ func parseHeaders(headers map[string][]string) http.Header {
}
_, hasAgent := h["User-Agent"]
if !hasAgent {
- h.Add("User-Agent", "goku-requests/"+Version)
+ h.Add("User-Agent", "goku-requests/"+requestVersion)
}
return h
}
// 解析请求体
-func (this *Request) parseBody() (req *http.Request, err error) {
+func (rq *Request) parseBody() (req *http.Request, err error) {
var body io.Reader = nil
- if len(this.body) > 0 {
- body = bytes.NewBuffer(this.body)
+ if len(rq.body) > 0 {
+ body = bytes.NewBuffer(rq.body)
}
- req, err = http.NewRequest(this.method, this.UrlPath(), body)
+ req, err = http.NewRequest(rq.method, rq.URLPath(), body)
return
- //if this.method == "GET" || this.method == "TRACE" {
- // req, err = http.NewRequest(this.method, this.UrlPath(), nil)
+ //if rq.method == "GET" || rq.method == "TRACE" {
+ // req, err = http.NewRequest(rq.method, rq.URLPath(), nil)
//}
//
- //if len(this.body) > 0 {
+ //if len(rq.body) > 0 {
//
- // if this.isJSON {
- // if _, ok := this.headers["Content-Type"]; !ok {
- // this.headers["Content-Type"] = []string{"application/json"}
+ // if rq.isJSON {
+ // if _, ok := rq.headers["Content-Type"]; !ok {
+ // rq.headers["Content-Type"] = []string{"application/json"}
// }
- // req, err = http.NewRequest(this.method, this.UrlPath(),
- // strings.NewReader(string(this.body)))
+ // req, err = http.NewRequest(rq.method, rq.URLPath(),
+ // strings.NewReader(string(rq.body)))
// } else {
// var body *bytes.Buffer
- // body = bytes.NewBuffer(this.body)
+ // body = bytes.NewBuffer(rq.body)
//
// }
- //} else if len(this.files) > 0 {
+ //} else if len(rq.files) > 0 {
// body := new(bytes.Buffer)
// writer := multipart.NewWriter(body)
// var part io.Writer
- // for fieldname, file := range this.files {
+ // for fieldname, file := range rq.files {
// part, err = writer.CreateFormFile(fieldname, file.filename)
// if err != nil {
// return
@@ -199,7 +199,7 @@ func (this *Request) parseBody() (req *http.Request, err error) {
// return
// }
// }
- // for fieldname, values := range this.formParams {
+ // for fieldname, values := range rq.formParams {
// temp := make(map[string][]string)
// temp[fieldname] = values
// value := parseParams(temp).Encode()
@@ -212,17 +212,17 @@ func (this *Request) parseBody() (req *http.Request, err error) {
// if err != nil {
// return
// }
- // this.headers["Content-Type"] = []string{writer.FormDataContentType()}
- // req, err = http.NewRequest(this.method, this.UrlPath(), body)
+ // rq.headers["Content-Type"] = []string{writer.FormDataContentType()}
+ // req, err = http.NewRequest(rq.method, rq.URLPath(), body)
//} else {
- // this.headers["Content-Type"] = []string{"application/x-www-form-urlencoded"}
- // req, err = http.NewRequest(this.method, this.UrlPath(),
- // strings.NewReader(parseParams(this.formParams).Encode()))
+ // rq.headers["Content-Type"] = []string{"application/x-www-form-urlencoded"}
+ // req, err = http.NewRequest(rq.method, rq.URLPath(),
+ // strings.NewReader(parseParams(rq.formParams).Encode()))
//}
//return
}
-// 解析参数
+//parseParams 解析参数
func parseParams(params map[string][]string) url.Values {
v := url.Values{}
for key, values := range params {
@@ -233,7 +233,7 @@ func parseParams(params map[string][]string) url.Values {
return v
}
-// 解析URL
+//parseURL 解析URL
func parseURL(urlPath string) (URL *url.URL, err error) {
URL, err = url.Parse(urlPath)
if err != nil {
diff --git a/goku-node/request_mapping.go b/goku-node/request_mapping.go
index 168bd1d..4580146 100644
--- a/goku-node/request_mapping.go
+++ b/goku-node/request_mapping.go
@@ -1,4 +1,4 @@
-package goku_node
+package gokunode
import (
"fmt"
@@ -13,13 +13,13 @@ import (
"strings"
)
-// 创建转发请求
-func CreateRequest(ctx *common.Context, apiInfo *entity.ApiExtend, timeout, retry int) (error, *http.Response) {
+// CreateRequest 创建转发请求
+func CreateRequest(ctx *common.Context, apiInfo *entity.APIExtend, timeout, retry int) (*http.Response, error) {
app, has := balance_manager.Get(apiInfo.Target)
if !has {
err := fmt.Errorf("get balance error:%s", apiInfo.Target)
- return err, nil
+ return nil, err
}
rawbody, _ := ctx.ProxyRequest.RawBody()
@@ -29,8 +29,8 @@ func CreateRequest(ctx *common.Context, apiInfo *entity.ApiExtend, timeout, retr
ctx.SetFinalTargetServer(finalTargetServer)
if err != nil {
- return err, nil
+ return nil, err
}
- return nil, response
+ return response, nil
}
diff --git a/goku-node/router.go b/goku-node/router.go
index 7f102b1..70bbd4f 100644
--- a/goku-node/router.go
+++ b/goku-node/router.go
@@ -1,4 +1,4 @@
-package goku_node
+package gokunode
import (
"fmt"
@@ -7,7 +7,7 @@ import (
access_log "github.com/eolinker/goku-api-gateway/goku-node/access-log"
"github.com/eolinker/goku-api-gateway/goku-node/handler"
"github.com/eolinker/goku-api-gateway/goku-node/plugin-flow"
- . "github.com/eolinker/goku-api-gateway/server/access-field"
+ access_field "github.com/eolinker/goku-api-gateway/server/access-field"
"net/http"
"strconv"
"strings"
@@ -26,6 +26,7 @@ import (
// "time"
)
+// Router 路由
type Router struct {
mu map[string]http.HandlerFunc
}
@@ -48,6 +49,7 @@ func (mux *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
+// NewRouter 创建新路由
func NewRouter() http.Handler {
r := &Router{
@@ -65,6 +67,7 @@ func NewRouter() http.Handler {
var systemRequestPath = []string{"/oauth2/token", "/oauth2/authorize", "/oauth2/verify"}
+//ServeHTTP httpHandle
func ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer func() {
if err := recover(); err != nil {
@@ -95,14 +98,14 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) {
if ctx.ProxyResponseHandler != nil {
proxyStatusCode = ctx.ProxyResponseHandler.StatusCode()
}
- logFields[RequestId] = requestID
- logFields[StatusCode] = status
- logFields[HttpUserAgent] = fmt.Sprint("\"", req.UserAgent(), "\"")
- logFields[HttpReferer] = req.Referer()
- logFields[RequestTime] = time.Since(timeStart)
- logFields[Request] = fmt.Sprint("\"", req.Method, " ", req.URL.Path, " ", req.Proto, "\"")
- logFields[BodyBytesSent] = n
- logFields[Host] = req.Host
+ logFields[access_field.RequestID] = requestID
+ logFields[access_field.StatusCode] = status
+ logFields[access_field.HTTPUserAgent] = fmt.Sprint("\"", req.UserAgent(), "\"")
+ logFields[access_field.HTTPReferer] = req.Referer()
+ logFields[access_field.RequestTime] = time.Since(timeStart)
+ logFields[access_field.Request] = fmt.Sprint("\"", req.Method, " ", req.URL.Path, " ", req.Proto, "\"")
+ logFields[access_field.BodyBytesSent] = n
+ logFields[access_field.Host] = req.Host
access_log.Log(logFields)
log.WithFields(logFields).Info()
@@ -111,25 +114,25 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) {
return
}
}
- apiId := strconv.Itoa(ctx.ApiID())
+ apiID := strconv.Itoa(ctx.ApiID())
- monitor_write.AddMonitor(ctx.StrategyId(), apiId, proxyStatusCode, ctx.StatusCode())
+ monitor_write.AddMonitor(ctx.StrategyId(), apiID, proxyStatusCode, ctx.StatusCode())
}()
remoteAddr := Intercept(req.RemoteAddr, ":")
- logFields[RemoteAddr] = remoteAddr
+ logFields[access_field.RemoteAddr] = remoteAddr
- if realIp := ctx.GetHeader("X-Real-Ip"); realIp == "" {
+ if realIP := ctx.GetHeader("X-Real-Ip"); realIP == "" {
ctx.ProxyRequest.SetHeader("X-Real-Ip", remoteAddr)
- logFields[HttpXForwardedFor] = remoteAddr
+ logFields[access_field.HTTPXForwardedFor] = remoteAddr
} else {
- logFields[HttpXForwardedFor] = realIp
+ logFields[access_field.HTTPXForwardedFor] = realIP
}
// 匹配URI前执行函数
var isBefor bool
start := time.Now()
- isBefor = plugin_flow.BeforeMatch(ctx)
+ isBefor = pluginflow.BeforeMatch(ctx)
log.Info(requestID, " BeforeMatch plugin duration:", time.Since(start))
if !isBefor {
log.Info(requestID, " stop by BeforeMatch plugin")
@@ -143,43 +146,43 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) {
return
}
- logFields[Strategy] = fmt.Sprintf("\"%s %s\"", strategyID, ctx.StrategyName())
+ logFields[access_field.Strategy] = fmt.Sprintf("\"%s %s\"", strategyID, ctx.StrategyName())
requestPath := req.URL.Path
requestMenthod := ctx.Request().Method()
var handleFunc []*entity.PluginHandlerExce
- apiInfo, splitURL, param, ok := strategy_api_manager.CheckApiFromStrategy(strategyID, requestPath, req.Method)
+ apiInfo, splitURL, param, ok := strategy_api_manager.CheckAPIFromStrategy(strategyID, requestPath, req.Method)
if ok {
- ctx.SetApiID(apiInfo.ApiID)
+ ctx.SetAPIID(apiInfo.APIID)
retryCount = apiInfo.RetryCount
//ctx.IsMatch = true
timeout = apiInfo.Timeout
ctx.ProxyRequest.SetTargetServer(fmt.Sprintf("%s://%s", apiInfo.Protocol, apiInfo.Target))
- targetUrl := apiInfo.TargetURL + requestPath
+ targetURL := apiInfo.TargetURL + requestPath
if apiInfo.StripPrefix {
- targetUrl = apiInfo.TargetURL + splitURL
+ targetURL = apiInfo.TargetURL + splitURL
}
if apiInfo.StripSlash {
- targetUrl = node_common.FilterSlash(targetUrl)
+ targetURL = node_common.FilterSlash(targetURL)
}
if !apiInfo.IsFollow {
ctx.ProxyRequest.Method = strings.ToUpper(apiInfo.TargetMethod)
}
- targetUrl = node_common.MatchRestful(targetUrl, param)
+ targetURL = node_common.MatchRestful(targetURL, param)
- ctx.ProxyRequest.SetTargetURL(targetUrl)
+ ctx.ProxyRequest.SetTargetURL(targetURL)
- handleFunc, _ = strategy_api_plugin_manager.GetPluginsOfApi(strategyID, apiInfo.ApiID)
+ handleFunc, _ = strategy_api_plugin_manager.GetPluginsOfAPI(strategyID, apiInfo.APIID)
} else {
handleFunc, _ = strategy_plugin_manager.GetPluginsOfStrategy(strategyID)
}
start = time.Now()
- isAccess, _ := plugin_flow.AccessFunc(ctx, handleFunc)
+ isAccess, _ := pluginflow.AccessFunc(ctx, handleFunc)
log.Info(requestID, " Access plugin duration:", time.Since(start))
if !isAccess {
@@ -194,17 +197,17 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) {
return
}
- logFields[Api] = fmt.Sprintf("\"%d %s\"", apiInfo.ApiID, apiInfo.ApiName)
- logFields[Proxy] = fmt.Sprintf("\"%s %s %s\"", ctx.ProxyRequest.Method, ctx.ProxyRequest.TargetURL(), apiInfo.Protocol)
- logFields[Balance] = apiInfo.Target
+ logFields[access_field.API] = fmt.Sprintf("\"%d %s\"", apiInfo.APIID, apiInfo.APIName)
+ logFields[access_field.Proxy] = fmt.Sprintf("\"%s %s %s\"", ctx.ProxyRequest.Method, ctx.ProxyRequest.TargetURL(), apiInfo.Protocol)
+ logFields[access_field.Balance] = apiInfo.Target
start = time.Now()
- err, response := CreateRequest(ctx, apiInfo, timeout, retryCount)
+ response, err := CreateRequest(ctx, apiInfo, timeout, retryCount)
log.Info(requestID, " Proxy request duration:", time.Since(start))
if err != nil {
log.Warn(err.Error())
}
- logFields[FinallyServer] = ctx.FinalTargetServer()
- logFields[Retry] = ctx.RetryTargetServers()
+ logFields[access_field.FinallyServer] = ctx.FinalTargetServer()
+ logFields[access_field.Retry] = ctx.RetryTargetServers()
ctx.SetProxyResponse(response)
form, _ := ctx.RequestOrg.BodyForm()
if response == nil {
@@ -220,7 +223,7 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctx)
} else {
- logFields[ProxyStatusCode] = response.StatusCode
+ logFields[access_field.ProxyStatusCode] = response.StatusCode
// w.WriteHeader(ctx.ProxyStatusCode)
if !gateway_manager.IsSucess(ctx.StatusCode()) {
go visit.UpdateProxyFailureCount(
@@ -237,7 +240,7 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) {
}
start = time.Now()
- isProxy, _ := plugin_flow.ProxyFunc(ctx, handleFunc)
+ isProxy, _ := pluginflow.ProxyFunc(ctx, handleFunc)
log.Info(requestID, " Proxy plugin Duration:", time.Since(start))
if !isProxy {
return
diff --git a/goku-node/server.go b/goku-node/server.go
index bd21c31..442e9ad 100644
--- a/goku-node/server.go
+++ b/goku-node/server.go
@@ -1,4 +1,4 @@
-package goku_node
+package gokunode
import (
log "github.com/eolinker/goku-api-gateway/goku-log"
@@ -14,19 +14,26 @@ import (
"strings"
)
+//InitPluginUtils 初始化插件工具
func InitPluginUtils() {
goku_plugin.SetRedisManager(redis_plugin_proxy.Create())
goku_plugin.InitLog(log.GetLogger())
//goku_plugin.SetLog(new(log_plugin_proxy.LoggerGeneral))
}
+
+//InitDiscovery 初始化服务发现
func InitDiscovery() {
all := discovery.AllDrivers()
log.Infof("install service discovery driver:[%s]\n", strings.Join(all, ","))
}
+
+//InitLog 初始化日志模块
func InitLog() {
config_manager.InitLog()
}
+
+//InitServer 初始化Server
func InitServer() {
log.Debug("init InitServer start")
diff --git a/goku-node/strategy.go b/goku-node/strategy.go
index 0b2e54f..1fea636 100644
--- a/goku-node/strategy.go
+++ b/goku-node/strategy.go
@@ -1,4 +1,4 @@
-package goku_node
+package gokunode
import (
log "github.com/eolinker/goku-api-gateway/goku-log"
diff --git a/goku-node/utils.go b/goku-node/utils.go
index c94353a..4e6b1c1 100644
--- a/goku-node/utils.go
+++ b/goku-node/utils.go
@@ -1,14 +1,12 @@
-package goku_node
+package gokunode
import (
- "bytes"
"math/rand"
- "runtime"
"strings"
"time"
)
-//生成随机字符串
+// GetRandomString 生成随机字符串
func GetRandomString(num int) string {
str := "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"
bytes := []byte(str)
@@ -20,6 +18,7 @@ func GetRandomString(num int) string {
return string(result)
}
+//Intercept 过滤子字符串
func Intercept(str, substr string) string {
result := strings.Index(str, substr)
var rs string
@@ -30,24 +29,3 @@ func Intercept(str, substr string) string {
}
return rs
}
-func PanicTrace(kb int) []byte {
- s := []byte("/src/runtime/panic.go")
- e := []byte("\ngoroutine ")
- line := []byte("\n")
- stack := make([]byte, kb<<10) //4KB
- length := runtime.Stack(stack, true)
- start := bytes.Index(stack, s)
- stack = stack[start:length]
- start = bytes.Index(stack, line) + 1
- stack = stack[start:]
- end := bytes.LastIndex(stack, line)
- if end != -1 {
- stack = stack[:end]
- }
- end = bytes.Index(stack, e)
- if end != -1 {
- stack = stack[:end]
- }
- stack = bytes.TrimRight(stack, "\n")
- return stack
-}
diff --git a/goku-node/visit/visit.go b/goku-node/visit/visit.go
index 8cf2814..3d3e4db 100644
--- a/goku-node/visit/visit.go
+++ b/goku-node/visit/visit.go
@@ -9,7 +9,7 @@ import (
node_common "github.com/eolinker/goku-api-gateway/goku-node/node-common"
- "github.com/eolinker/goku-api-gateway/common/redis-manager"
+ redis_manager "github.com/eolinker/goku-api-gateway/common/redis-manager"
cmd2 "github.com/eolinker/goku-api-gateway/goku-node/cmd"
gateway_manager "github.com/eolinker/goku-api-gateway/goku-node/manager/gateway-manager"
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
@@ -22,8 +22,8 @@ type alertInfo struct {
ReceiveList string `json:"receiveList"`
}
-// 更新网关转发失败次数
-func UpdateProxyFailureCount(apiInfo *entity.ApiExtend,
+//UpdateProxyFailureCount 更新网关转发失败次数
+func UpdateProxyFailureCount(apiInfo *entity.APIExtend,
requestMethod string,
proxyMethod string,
headers map[string][]string,
@@ -66,7 +66,7 @@ func UpdateProxyFailureCount(apiInfo *entity.ApiExtend,
}
// 获取当前告警时间信息
- redisKey := clusterName + ":gokuFailureCount:" + strconv.Itoa(apiInfo.ApiID)
+ redisKey := clusterName + ":gokuFailureCount:" + strconv.Itoa(apiInfo.APIID)
// 获取key信息
result, err := redisConn.Get(redisKey).Result()
if err != nil {
@@ -129,8 +129,8 @@ func UpdateProxyFailureCount(apiInfo *entity.ApiExtend,
if count >= apiInfo.AlertValve {
- _, _, _ = cmd2.AddAlertMessage(apiInfo.ApiID,
- apiInfo.ApiName,
+ _, _, _ = cmd2.AddAlertMessage(apiInfo.APIID,
+ apiInfo.APIName,
apiInfo.RequestURL,
ctx.FinalTargetServer(),
apiInfo.TargetURL,
@@ -173,7 +173,7 @@ func UpdateProxyFailureCount(apiInfo *entity.ApiExtend,
period = "60"
}
msg := "[Alert] GoKu Gateway failed to proxy requests for " + period + " minute " + strconv.Itoa(apiInfo.AlertValve) + " times"
- cmd2.SendRequestToAlertAddress(alertAddress, apiInfo.RequestURL, ctx.FinalTargetServer(), apiInfo.TargetURL, msg, apiInfo.ApiName, apiInfo.ApiID)
+ cmd2.SendRequestToAlertAddress(alertAddress, apiInfo.RequestURL, ctx.FinalTargetServer(), apiInfo.TargetURL, msg, apiInfo.APIName, apiInfo.APIID)
_, err = redisConn.Set(redisKey, 1, time.Duration(expire)*time.Second).Result()
if err != nil {
@@ -181,8 +181,8 @@ func UpdateProxyFailureCount(apiInfo *entity.ApiExtend,
}
} else {
_, _, _ = cmd2.AddAlertMessage(
- apiInfo.ApiID,
- apiInfo.ApiName,
+ apiInfo.APIID,
+ apiInfo.APIName,
apiInfo.RequestURL,
ctx.FinalTargetServer(),
apiInfo.TargetURL,
@@ -223,7 +223,7 @@ func UpdateProxyFailureCount(apiInfo *entity.ApiExtend,
}
}
-// 记录告警日志
+//AlertLog 记录告警日志
func AlertLog(requestURL, targetServer, targetURL, requestMethod, proxyMethod, headerList, queryParamList, formParamList, responseHeaderList string, responseStatus int, strategyID string, strategyName, requestID string) {
log.WithFields(log.Fields{
"request_id": requestID,
diff --git a/goku-service/application/request.go b/goku-service/application/request.go
index 154d0f7..21ba0ea 100644
--- a/goku-service/application/request.go
+++ b/goku-service/application/request.go
@@ -121,7 +121,7 @@ func (this *Request) QueryParams() map[string][]string {
}
// 获取完整的URL路径
-func (this *Request) UrlPath() string {
+func (this *Request) URLPath() string {
if len(this.queryParams) > 0 {
return this.URL + "?" + parseParams(this.queryParams).Encode()
} else {
@@ -166,10 +166,10 @@ func (this *Request) parseBody() (req *http.Request, err error) {
body = bytes.NewBuffer(this.body)
}
- req, err = http.NewRequest(this.method, this.UrlPath(), body)
+ req, err = http.NewRequest(this.method, this.URLPath(), body)
return
//if this.method == "GET" || this.method == "TRACE" {
- // req, err = http.NewRequest(this.method, this.UrlPath(), nil)
+ // req, err = http.NewRequest(this.method, this.URLPath(), nil)
//}
//
//if len(this.body) > 0 {
@@ -178,7 +178,7 @@ func (this *Request) parseBody() (req *http.Request, err error) {
// if _, ok := this.headers["Content-Type"]; !ok {
// this.headers["Content-Type"] = []string{"application/json"}
// }
- // req, err = http.NewRequest(this.method, this.UrlPath(),
+ // req, err = http.NewRequest(this.method, this.URLPath(),
// strings.NewReader(string(this.body)))
// } else {
// var body *bytes.Buffer
@@ -213,10 +213,10 @@ func (this *Request) parseBody() (req *http.Request, err error) {
// return
// }
// this.headers["Content-Type"] = []string{writer.FormDataContentType()}
- // req, err = http.NewRequest(this.method, this.UrlPath(), body)
+ // req, err = http.NewRequest(this.method, this.URLPath(), body)
//} else {
// this.headers["Content-Type"] = []string{"application/x-www-form-urlencoded"}
- // req, err = http.NewRequest(this.method, this.UrlPath(),
+ // req, err = http.NewRequest(this.method, this.URLPath(),
// strings.NewReader(parseParams(this.formParams).Encode()))
//}
//return
diff --git a/server/access-field/def.go b/server/access-field/def.go
index 39f1fd1..78b41e3 100644
--- a/server/access-field/def.go
+++ b/server/access-field/def.go
@@ -1,32 +1,54 @@
-package access_field
+package accessfield
import "strings"
+//AccessFieldKey access日志域的键名
type AccessFieldKey string
const (
+ //RemoteAddr remote_addr
RemoteAddr = "$remote_addr"
- HttpXForwardedFor = "$http_x_forwarded_for"
- Request = "$request"
- StatusCode = "$status_code"
- BodyBytesSent = "$body_bytes_sent"
- Msec = "$msec"
- HttpReferer = "$http_referer"
- HttpUserAgent = "$http_user_agent"
- RequestTime = "$request_time"
- TimeIso8601 = "$time_iso8601"
- TimeLocal = "$time_local"
- RequestId = "$request_id"
- FinallyServer = "$finally_server"
- Balance = "$balance"
- Strategy = "$strategy"
- Api = "$api"
- Retry = "$retry"
- Proxy = "$proxy"
- ProxyStatusCode = "$proxy_status_code"
- Host = "$host"
+ //HTTPXForwardedFor http_x_forwarded_for
+ HTTPXForwardedFor = "$http_x_forwarded_for"
+ //Request request
+ Request = "$request"
+ //StatusCode status_code
+ StatusCode = "$status_code"
+ //BodyBytesSent body_bytes_sent
+ BodyBytesSent = "$body_bytes_sent"
+ //Msec msec
+ Msec = "$msec"
+ //HTTPReferer http_referer
+ HTTPReferer = "$http_referer"
+ //HTTPUserAgent http_user_agent
+ HTTPUserAgent = "$http_user_agent"
+ //RequestTime request_time
+ RequestTime = "$request_time"
+ //TimeIso8601 time_iso8601
+ TimeIso8601 = "$time_iso8601"
+ //TimeLocal time_local
+ TimeLocal = "$time_local"
+ //RequestID request_id
+ RequestID = "$request_id"
+ //FinallyServer finally_server
+ FinallyServer = "$finally_server"
+ //Balance balance
+ Balance = "$balance"
+ //Strategy strategy
+ Strategy = "$strategy"
+ //API api
+ API = "$api"
+ //Retry retry
+ Retry = "$retry"
+ //Proxy proxy
+ Proxy = "$proxy"
+ //ProxyStatusCode proxy_status_code
+ ProxyStatusCode = "$proxy_status_code"
+ //Host host
+ Host = "$host"
)
+//Info info
func (k AccessFieldKey) Info() string {
key := strings.ToLower(string(k))
v, has := infos[key]
@@ -35,14 +57,19 @@ func (k AccessFieldKey) Info() string {
}
return "unknown"
}
+
+//Key key
func (k AccessFieldKey) Key() string {
return strings.ToLower(string(k))
}
+//Parse parse
func Parse(key string) AccessFieldKey {
return AccessFieldKey(strings.ToLower(key))
}
+
+//CopyKey copy key
func CopyKey() map[string]string {
v := make(map[string]string)
for key, value := range infos {
@@ -50,6 +77,8 @@ func CopyKey() map[string]string {
}
return v
}
+
+//Has 判断key是否存在
func Has(key string) bool {
_, has := infos[AccessFieldKey(key).Key()]
return has
diff --git a/server/access-field/info.go b/server/access-field/info.go
index 9608d33..105afa4 100644
--- a/server/access-field/info.go
+++ b/server/access-field/info.go
@@ -1,26 +1,26 @@
-package access_field
+package accessfield
var (
infos = map[string]string{
RemoteAddr: "记录客户端IP地址",
- HttpXForwardedFor: "记录客户端IP地址(反向)",
+ HTTPXForwardedFor: "记录客户端IP地址(反向)",
Request: "记录请求的方法、URL和协议(例如 POST /proxy HTTPS)",
StatusCode: "记录请求状态",
- BodyBytesSent: "发送给客户端的字节数,不包括响应头的大小; 该变量与Apache模块mod_log_config里的“%B”参数兼容。",
- Msec: "日志写入时间。单位为秒,精度是毫秒。",
- HttpReferer: "记录从哪个页面链接访问过来的",
- HttpUserAgent: "记录客户端浏览器相关信息",
- RequestTime: "请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始,直到把最后一个字符发送给客户端后进行日志写入为止。",
- TimeIso8601: "ISO8601标准格式下的本地时间。",
- TimeLocal: "通用日志格式下的本地时间。",
- RequestId: "请求id",
- FinallyServer: "最后一次转发的主机信息(IP端口或域名端口)",
- Balance: "负载信息",
- Strategy: "策略信息,包括策略名称和ID",
- Api: "API信息,包括 API名称和ID",
- Retry: "重试信息",
- Proxy: "记录转发的方法、URL和协议(例如 POST /proxy HTTPS)",
- ProxyStatusCode: "转发状态码",
- Host: "主机信息",
+ BodyBytesSent: "发送给客户端的字节数,不包括响应头的大小; 该变量与Apache模块mod_log_config里的“%B”参数兼容。",
+ Msec: "日志写入时间。单位为秒,精度是毫秒。",
+ HTTPReferer: "记录从哪个页面链接访问过来的",
+ HTTPUserAgent: "记录客户端浏览器相关信息",
+ RequestTime: "请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始,直到把最后一个字符发送给客户端后进行日志写入为止。",
+ TimeIso8601: "ISO8601标准格式下的本地时间。",
+ TimeLocal: "通用日志格式下的本地时间。",
+ RequestID: "请求id",
+ FinallyServer: "最后一次转发的主机信息(IP端口或域名端口)",
+ Balance: "负载信息",
+ Strategy: "策略信息,包括策略名称和ID",
+ API: "API信息,包括 API名称和ID",
+ Retry: "重试信息",
+ Proxy: "记录转发的方法、URL和协议(例如 POST /proxy HTTPS)",
+ ProxyStatusCode: "转发状态码",
+ Host: "主机信息",
}
)
diff --git a/server/access-field/select.go b/server/access-field/select.go
index db8bfd7..85a8e56 100644
--- a/server/access-field/select.go
+++ b/server/access-field/select.go
@@ -1,12 +1,12 @@
-package access_field
+package accessfield
var (
defaultFields = []AccessFieldKey{
- RequestId,
+ RequestID,
TimeIso8601,
Strategy,
- Api,
+ API,
Host,
Request,
Balance,
@@ -16,7 +16,7 @@ var (
ProxyStatusCode,
RequestTime,
RemoteAddr,
- HttpXForwardedFor,
+ HTTPXForwardedFor,
Retry,
}
@@ -28,11 +28,15 @@ func init() {
defaultSet[k] = true
}
}
+
+//IsDefault 是否有默认值
func IsDefault(k AccessFieldKey) bool {
_, has := defaultSet[k]
return has
}
+
+//Default 获取默认的字段
func Default() []AccessFieldKey {
return defaultFields
diff --git a/server/access-field/sort.go b/server/access-field/sort.go
index 9fa3fda..fa14ec6 100644
--- a/server/access-field/sort.go
+++ b/server/access-field/sort.go
@@ -1,13 +1,13 @@
-package access_field
+package accessfield
var (
all = []AccessFieldKey{
- RequestId,
+ RequestID,
Msec,
TimeLocal,
TimeIso8601,
Strategy,
- Api,
+ API,
Host,
Request,
Balance,
@@ -17,18 +17,21 @@ var (
ProxyStatusCode,
RequestTime,
RemoteAddr,
- HttpXForwardedFor,
+ HTTPXForwardedFor,
Retry,
BodyBytesSent,
- HttpReferer,
- HttpUserAgent,
+ HTTPReferer,
+ HTTPUserAgent,
}
size = len(all)
)
+//Size 返回size
func Size() int {
return size
}
+
+//All all
func All() []AccessFieldKey {
return all
}
diff --git a/server/cluster/cluster.go b/server/cluster/cluster.go
index cbe5189..9a0b3a5 100644
--- a/server/cluster/cluster.go
+++ b/server/cluster/cluster.go
@@ -4,11 +4,12 @@ import "github.com/eolinker/goku-api-gateway/server/entity"
var (
byName map[string]*entity.ClusterInfo
- byId map[int]*entity.ClusterInfo
+ byID map[int]*entity.ClusterInfo
clusterInfos []*entity.ClusterInfo
nodes []*entity.Cluster
)
+//Init 初始化集群
func Init(cs []*entity.ClusterInfo) {
nt := make(map[string]*entity.ClusterInfo)
it := make(map[int]*entity.ClusterInfo)
@@ -16,46 +17,53 @@ func Init(cs []*entity.ClusterInfo) {
cis := make([]*entity.ClusterInfo, 0, len(cs))
for _, c := range cs {
nt[c.Name] = c
- it[c.Id] = c
+ it[c.ID] = c
ns = append(ns, c.Cluster())
cis = append(cis, c)
}
byName = nt
- byId = it
+ byID = it
clusterInfos = cis
nodes = ns
}
+
+//Get 根据集群名获取集群信息
func Get(name string) (*entity.ClusterInfo, bool) {
v, has := byName[name]
return v, has
}
+//GetAll 获取所有集群信息
func GetAll() []*entity.ClusterInfo {
return clusterInfos
}
+//GetList 获取集群列表
func GetList() []*entity.Cluster {
return nodes
}
-func GetId(name string) (id int, has bool) {
+//GetID 通过集群名获取集群ID
+func GetID(name string) (id int, has bool) {
v, h := byName[name]
if !h {
return 0, false
}
- return v.Id, true
+ return v.ID, true
}
+//GetClusterCount 获取集群数量
func GetClusterCount() int {
return len(nodes)
}
-func GetById(id int) (*entity.ClusterInfo, bool) {
- v, h := byId[id]
+//GetByID 通过ID获取集群信息
+func GetByID(id int) (*entity.ClusterInfo, bool) {
+ v, h := byID[id]
return v, h
}
diff --git a/server/dao/config-log/log.go b/server/dao/config-log/log.go
index 3f1453a..e96a364 100644
--- a/server/dao/config-log/log.go
+++ b/server/dao/config-log/log.go
@@ -1,4 +1,4 @@
-package config_log
+package configlog
import (
"github.com/eolinker/goku-api-gateway/common/database"
@@ -8,6 +8,7 @@ import (
const sqlSelect = "SELECT `name`,`enable`,`dir`,`file`,`level`,`period`,`expire`,`fields` FROM `goku_config_log` WHERE `name` = ? LIMIT 1;"
const sqlInsert = "INSERT INTO `goku_config_log`(`name`,`enable`,`dir`,`file`,`level`,`period`,`expire`,`fields`)VALUES(?,?,?,?,?,?,?,?)ON DUPLICATE KEY UPDATE `enable`=VALUES(`enable`),`dir`=VALUES(`dir`),`file`=VALUES(`file`),`level`=VALUES(`level`),`period`=VALUES(`period`),`expire`=VALUES(`expire`),`fields`=VALUES(`fields`);"
+//Get 通过名称获取日志配置
func Get(name string) (*entity.LogConfig, error) {
stmt, e := database.GetConnection().Prepare(sqlSelect)
if e != nil {
@@ -30,6 +31,7 @@ func Get(name string) (*entity.LogConfig, error) {
return ent, nil
}
+//Set 设置日志配置
func Set(ent *entity.LogConfig) error {
stmt, e := database.GetConnection().Prepare(sqlInsert)
if e != nil {
diff --git a/server/dao/console-mysql/alert.go b/server/dao/console-mysql/alert.go
index 703f1b7..f093ad1 100644
--- a/server/dao/console-mysql/alert.go
+++ b/server/dao/console-mysql/alert.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
"encoding/json"
@@ -8,7 +8,7 @@ import (
database2 "github.com/eolinker/goku-api-gateway/common/database"
)
-// 获取告警信息列表
+// GetAlertMsgList 获取告警信息列表
func GetAlertMsgList(page, pageSize int) (bool, []map[string]interface{}, int, error) {
db := database2.GetConnection()
var count int
@@ -41,7 +41,7 @@ func GetAlertMsgList(page, pageSize int) (bool, []map[string]interface{}, int, e
} else if alertPeriodType == 4 {
period = "60"
}
- var msg string = "网关转发失败" + period + "分钟达到" + strconv.Itoa(alertCount) + "次"
+ var msg = "网关转发失败" + period + "分钟达到" + strconv.Itoa(alertCount) + "次"
alertInfo := map[string]interface{}{
"alertID": alertID,
"requestURL": requestURL,
@@ -58,7 +58,7 @@ func GetAlertMsgList(page, pageSize int) (bool, []map[string]interface{}, int, e
return true, alertList, count, nil
}
-// 清空告警信息列表
+// ClearAlertMsg 清空告警信息列表
func ClearAlertMsg() (bool, string, error) {
db := database2.GetConnection()
sql := "DELETE FROM goku_gateway_alert;"
@@ -69,7 +69,7 @@ func ClearAlertMsg() (bool, string, error) {
return true, "", nil
}
-// 删除告警信息
+// DeleteAlertMsg 删除告警信息
func DeleteAlertMsg(alertID int) (bool, string, error) {
db := database2.GetConnection()
sql := "DELETE FROM goku_gateway_alert WHERE alertID = ?;"
@@ -80,7 +80,7 @@ func DeleteAlertMsg(alertID int) (bool, string, error) {
return true, "", nil
}
-// 新增告警信息
+// AddAlertMsg 新增告警信息
func AddAlertMsg(requestURL, targetServer, targetURL, ip, clusterName string, alertPeriodType, alertCount int) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -92,6 +92,7 @@ func AddAlertMsg(requestURL, targetServer, targetURL, ip, clusterName string, al
return true, "", nil
}
+//GetAlertConfig 获取告警配置
func GetAlertConfig() (bool, map[string]interface{}, error) {
db := database2.GetConnection()
var apiAlertInfo, sender, senderPassword, smtpAddress string
@@ -102,14 +103,14 @@ func GetAlertConfig() (bool, map[string]interface{}, error) {
return false, nil, err
}
- apiAlertInfoJson := map[string]interface{}{}
+ apiAlertInfoJSON := map[string]interface{}{}
if apiAlertInfo == "" || apiAlertInfo == "{}" {
- apiAlertInfoJson["alertPeriodType"] = 0
- apiAlertInfoJson["alertAddr"] = ""
- apiAlertInfoJson["receiverList"] = ""
+ apiAlertInfoJSON["alertPeriodType"] = 0
+ apiAlertInfoJSON["alertAddr"] = ""
+ apiAlertInfoJSON["receiverList"] = ""
} else {
- err = json.Unmarshal([]byte(apiAlertInfo), &apiAlertInfoJson)
+ err = json.Unmarshal([]byte(apiAlertInfo), &apiAlertInfoJSON)
if err != nil {
return false, nil, err
}
@@ -122,7 +123,7 @@ func GetAlertConfig() (bool, map[string]interface{}, error) {
"smtpAddress": smtpAddress,
"smtpPort": smtpPort,
"smtpProtocol": smtpProtocol,
- "apiAlertInfo": apiAlertInfoJson,
+ "apiAlertInfo": apiAlertInfoJSON,
}
return true, gatewayConfig, nil
}
diff --git a/server/dao/console-mysql/api.go b/server/dao/console-mysql/api.go
index 79c3ce9..8740281 100644
--- a/server/dao/console-mysql/api.go
+++ b/server/dao/console-mysql/api.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
SQL "database/sql"
@@ -11,8 +11,8 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// AddApi 新增接口
-func AddApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol string, projectID, groupID, timeout, retryCount, alertValve, managerID, userID int) (bool, int, error) {
+// AddAPI 新增接口
+func AddAPI(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol string, projectID, groupID, timeout, retryCount, alertValve, managerID, userID int) (bool, int, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
Tx, _ := db.Begin()
@@ -21,21 +21,20 @@ func AddApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollo
if err != nil {
Tx.Rollback()
return false, 0, err
- } else {
- apiID, _ := res.LastInsertId()
- // 更新项目更新时间
- _, err = Tx.Exec("UPDATE goku_gateway_project SET updateTime = ? WHERE projectID = ?;", now, projectID)
- if err != nil {
- Tx.Rollback()
- return false, 0, err
- }
- Tx.Commit()
- return true, int(apiID), nil
}
+ apiID, _ := res.LastInsertId()
+ // 更新项目更新时间
+ _, err = Tx.Exec("UPDATE goku_gateway_project SET updateTime = ? WHERE projectID = ?;", now, projectID)
+ if err != nil {
+ Tx.Rollback()
+ return false, 0, err
+ }
+ Tx.Commit()
+ return true, int(apiID), nil
}
-// EditApi 新增接口
-func EditApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol string, projectID, groupID, timeout, retryCount, alertValve, apiID, managerID, userID int) (bool, error) {
+// EditAPI 新增接口
+func EditAPI(apiName, requestURL, targetURL, requestMethod, targetMethod, isFollow, stripPrefix, stripSlash, balanceName, protocol string, projectID, groupID, timeout, retryCount, alertValve, apiID, managerID, userID int) (bool, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
Tx, _ := db.Begin()
@@ -44,28 +43,27 @@ func EditApi(apiName, requestURL, targetURL, requestMethod, targetMethod, isFoll
if err != nil {
Tx.Rollback()
return false, err
- } else {
- // 更新项目更新时间
- _, err = Tx.Exec("UPDATE goku_gateway_project SET updateTime = ? WHERE projectID = ?;", now, projectID)
- if err != nil {
- Tx.Rollback()
- return false, err
- }
- Tx.Commit()
- return true, nil
}
+ // 更新项目更新时间
+ _, err = Tx.Exec("UPDATE goku_gateway_project SET updateTime = ? WHERE projectID = ?;", now, projectID)
+ if err != nil {
+ Tx.Rollback()
+ return false, err
+ }
+ Tx.Commit()
+ return true, nil
}
-// GetApiInfo 获取接口信息
-func GetApiInfo(apiID int) (bool, *entity.Api, error) {
+// GetAPIInfo 获取接口信息
+func GetAPIInfo(apiID int) (bool, *entity.API, error) {
db := database2.GetConnection()
sql := `SELECT goku_gateway_api.apiID,goku_gateway_api.groupID,goku_gateway_api.apiName,goku_gateway_api.requestURL,goku_gateway_api.targetURL,goku_gateway_api.requestMethod,goku_gateway_api.targetMethod,IFNULL(goku_gateway_api.protocol,"http"),goku_gateway_api.stripSlash,IFNULL(goku_gateway_api.balanceName,""),goku_gateway_api.isFollow,goku_gateway_api.stripPrefix,goku_gateway_api.timeout,goku_gateway_api.retryCount,goku_gateway_api.alertValve,goku_gateway_api.createTime,goku_gateway_api.updateTime,goku_gateway_api.managerID,goku_gateway_api.lastUpdateUserID,goku_gateway_api.createUserID,IFNULL(goku_gateway_api_group.groupPath,"0") FROM goku_gateway_api LEFT JOIN goku_gateway_api_group ON goku_gateway_api.groupID = goku_gateway_api_group.groupID WHERE goku_gateway_api.apiID = ?`
- api := &entity.Api{}
+ api := &entity.API{}
var managerInfo entity.ManagerInfo
- err := db.QueryRow(sql, apiID).Scan(&api.ApiID, &api.GroupID, &api.ApiName, &api.RequestURL, &api.ProxyURL, &api.RequestMethod, &api.TargetMethod, &api.Protocol, &api.StripSlash, &api.BalanceName, &api.IsFollow, &api.StripPrefix, &api.Timeout, &api.RetryConut, &api.Valve, &api.CreateTime, &api.UpdateTime, &managerInfo.ManagerID, &managerInfo.UpdaterID, &managerInfo.CreateUserID, &api.GroupPath)
+ err := db.QueryRow(sql, apiID).Scan(&api.APIID, &api.GroupID, &api.APIName, &api.RequestURL, &api.ProxyURL, &api.RequestMethod, &api.TargetMethod, &api.Protocol, &api.StripSlash, &api.BalanceName, &api.IsFollow, &api.StripPrefix, &api.Timeout, &api.RetryConut, &api.Valve, &api.CreateTime, &api.UpdateTime, &managerInfo.ManagerID, &managerInfo.UpdaterID, &managerInfo.CreateUserID, &api.GroupPath)
if err != nil {
panic(err)
- return false, &entity.Api{}, err
+ return false, &entity.API{}, err
}
api.RequestMethod = strings.ToUpper(api.RequestMethod)
@@ -74,13 +72,13 @@ func GetApiInfo(apiID int) (bool, *entity.Api, error) {
err = db.QueryRow(sql, managerInfo.ManagerID).Scan(&managerInfo.ManagerName)
if err != nil {
if err != SQL.ErrNoRows {
- return false, &entity.Api{}, err
+ return false, &entity.API{}, err
}
}
err = db.QueryRow(sql, managerInfo.UpdaterID).Scan(&managerInfo.UpdaterName)
if err != nil {
if err != SQL.ErrNoRows {
- return false, &entity.Api{}, err
+ return false, &entity.API{}, err
}
}
err = db.QueryRow(sql, managerInfo.CreateUserID).Scan(&managerInfo.CreateUserName)
@@ -93,8 +91,8 @@ func GetApiInfo(apiID int) (bool, *entity.Api, error) {
return true, api, nil
}
-// 通过分组列表获取接口列表
-func GetApiListByGroupList(projectID int, groupIDList string) (bool, []map[string]interface{}, error) {
+// GetAPIListByGroupList 通过分组列表获取接口列表
+func GetAPIListByGroupList(projectID int, groupIDList string) (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
// 获取分组ID列表
sql := `SELECT goku_gateway_api.apiID,goku_gateway_api.apiName,goku_gateway_api.requestURL,IFNULL(goku_gateway_api.updateTime,""),goku_gateway_api.lastUpdateUserID,goku_gateway_api.managerID FROM goku_gateway_api WHERE goku_gateway_api.projectID = ? AND goku_gateway_api.groupID IN (` + groupIDList + `) ORDER BY goku_gateway_api.updateTime DESC;`
@@ -108,37 +106,36 @@ func GetApiListByGroupList(projectID int, groupIDList string) (bool, []map[strin
//获取记录列
if _, err = rows.Columns(); err != nil {
return false, make([]map[string]interface{}, 0), err
- } else {
- for rows.Next() {
- var apiID, updaterID, managerID int
- var apiName, requestURL, updateTime, managerName, updaterName string
- err = rows.Scan(&apiID, &apiName, &requestURL, &updateTime, &updaterID, &managerID)
- if err != nil {
+ }
+ for rows.Next() {
+ var apiID, updaterID, managerID int
+ var apiName, requestURL, updateTime, managerName, updaterName string
+ err = rows.Scan(&apiID, &apiName, &requestURL, &updateTime, &updaterID, &managerID)
+ if err != nil {
+ return false, make([]map[string]interface{}, 0), err
+ }
+ sql = `SELECT IFNULL(remark,loginCall) as userName FROM goku_admin WHERE userID = ?;`
+ err = db.QueryRow(sql, managerID).Scan(&managerName)
+ if err != nil {
+ if err != SQL.ErrNoRows {
return false, make([]map[string]interface{}, 0), err
}
- sql = `SELECT IFNULL(remark,loginCall) as userName FROM goku_admin WHERE userID = ?;`
- err = db.QueryRow(sql, managerID).Scan(&managerName)
- if err != nil {
- if err != SQL.ErrNoRows {
- return false, make([]map[string]interface{}, 0), err
- }
- }
- err = db.QueryRow(sql, updaterID).Scan(&updaterName)
- if err != nil {
- if err != SQL.ErrNoRows {
- return false, make([]map[string]interface{}, 0), err
- }
- }
- apiInfo := map[string]interface{}{
- "apiID": apiID,
- "apiName": apiName,
- "requestURL": requestURL,
- "updateTime": updateTime,
- "updaterName": updaterName,
- "managerName": managerName,
+ }
+ err = db.QueryRow(sql, updaterID).Scan(&updaterName)
+ if err != nil {
+ if err != SQL.ErrNoRows {
+ return false, make([]map[string]interface{}, 0), err
}
- apiList = append(apiList, apiInfo)
}
+ apiInfo := map[string]interface{}{
+ "apiID": apiID,
+ "apiName": apiName,
+ "requestURL": requestURL,
+ "updateTime": updateTime,
+ "updaterName": updaterName,
+ "managerName": managerName,
+ }
+ apiList = append(apiList, apiInfo)
}
return true, apiList, nil
}
@@ -311,7 +308,7 @@ func GetAPIList(projectID int, groupID int, keyword string, condition, page, pag
return true, apiList, count, nil
}
-// 接口路径是否存在
+// CheckURLIsExist 接口路径是否存在
func CheckURLIsExist(requestURL, requestMethod string, projectID, apiID int) bool {
db := database2.GetConnection()
var id int
@@ -336,21 +333,20 @@ func CheckURLIsExist(requestURL, requestMethod string, projectID, apiID int) boo
return false
}
-// 检查接口是否存在
-func CheckApiIsExist(apiID int) (bool, error) {
+// CheckAPIIsExist CheckAPIIsExist 检查接口是否存在
+func CheckAPIIsExist(apiID int) (bool, error) {
db := database2.GetConnection()
sql := "SELECT apiID FROM goku_gateway_api WHERE apiID = ?;"
var id int
err := db.QueryRow(sql, apiID).Scan(&id)
if err != nil {
return false, err
- } else {
- return true, err
}
+ return true, err
}
-// 批量修改接口负载
-func BatchEditApiBalance(apiIDList []string, balance string) (string, error) {
+// BatchEditAPIBalance 批量修改接口负载
+func BatchEditAPIBalance(apiIDList []string, balance string) (string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -369,8 +365,8 @@ func BatchEditApiBalance(apiIDList []string, balance string) (string, error) {
return "", nil
}
-// 批量修改接口分组
-func BatchEditApiGroup(apiIDList []string, groupID int) (string, error) {
+// BatchEditAPIGroup 批量修改接口分组
+func BatchEditAPIGroup(apiIDList []string, groupID int) (string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -389,8 +385,8 @@ func BatchEditApiGroup(apiIDList []string, groupID int) (string, error) {
}
-// 批量修改接口
-func BatchDeleteApi(apiIDList string) (bool, string, error) {
+// BatchDeleteAPI 批量修改接口
+func BatchDeleteAPI(apiIDList string) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
Tx, _ := db.Begin()
diff --git a/server/dao/console-mysql/apiGroup.go b/server/dao/console-mysql/apiGroup.go
index 6410652..2b65ee0 100644
--- a/server/dao/console-mysql/apiGroup.go
+++ b/server/dao/console-mysql/apiGroup.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
SQL "database/sql"
@@ -9,8 +9,8 @@ import (
log "github.com/eolinker/goku-api-gateway/goku-log"
)
-// 新建接口分组
-func AddApiGroup(groupName string, projectID, parentGroupID int) (bool, interface{}, error) {
+// AddAPIGroup 新建接口分组
+func AddAPIGroup(groupName string, projectID, parentGroupID int) (bool, interface{}, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
Tx, _ := db.Begin()
@@ -48,8 +48,8 @@ func AddApiGroup(groupName string, projectID, parentGroupID int) (bool, interfac
if groupPath == "" {
groupPath = strconv.Itoa(int(groupID))
} else {
- groupDepth += 1
- groupPath += "," + strconv.Itoa(int(groupID))
+ groupDepth = groupDepth + 1
+ groupPath = groupPath + "," + strconv.Itoa(int(groupID))
}
// 更新groupDepth和groupPath
@@ -69,8 +69,8 @@ func AddApiGroup(groupName string, projectID, parentGroupID int) (bool, interfac
return true, groupID, nil
}
-// 修改接口分组
-func EditApiGroup(groupName string, groupID, projectID int) (bool, string, error) {
+// EditAPIGroup 修改接口分组
+func EditAPIGroup(groupName string, groupID, projectID int) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
Tx, _ := db.Begin()
@@ -90,8 +90,8 @@ func EditApiGroup(groupName string, groupID, projectID int) (bool, string, error
return true, "", nil
}
-// 删除接口分组
-func DeleteApiGroup(projectID, groupID int) (bool, string, error) {
+// DeleteAPIGroup 删除接口分组
+func DeleteAPIGroup(projectID, groupID int) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
var groupPath string
@@ -115,7 +115,7 @@ func DeleteApiGroup(projectID, groupID int) (bool, string, error) {
Tx.Rollback()
return false, "[ERROR]Fail to delete data!", err
}
- flag, apiList, _ := GetApiListByGroupList(projectID, concatGroupID)
+ flag, apiList, _ := GetAPIListByGroupList(projectID, concatGroupID)
if flag {
listLen := len(apiList)
if listLen > 0 {
@@ -172,8 +172,8 @@ func DeleteApiGroup(projectID, groupID int) (bool, string, error) {
return true, "", nil
}
-// 获取接口分组列表
-func GetApiGroupList(projectID int) (bool, []map[string]interface{}, error) {
+// GetAPIGroupList 获取接口分组列表
+func GetAPIGroupList(projectID int) (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
sql := "SELECT groupID,groupName,parentGroupID,groupDepth FROM goku_gateway_api_group WHERE projectID = ?;"
rows, err := db.Query(sql, projectID)
@@ -186,29 +186,28 @@ func GetApiGroupList(projectID int) (bool, []map[string]interface{}, error) {
info := err.Error()
log.Info(info)
return false, make([]map[string]interface{}, 0), err
- } else {
- groupList := make([]map[string]interface{}, 0)
- for rows.Next() {
- var groupID, parentGroupID, groupDepth int
- var groupName string
- err = rows.Scan(&groupID, &groupName, &parentGroupID, &groupDepth)
- if err != nil {
- return false, make([]map[string]interface{}, 0), err
- }
- groupInfo := map[string]interface{}{
- "groupID": groupID,
- "groupName": groupName,
- "groupDepth": groupDepth,
- "parentGroupID": parentGroupID,
- }
- groupList = append(groupList, groupInfo)
+ }
+ groupList := make([]map[string]interface{}, 0)
+ for rows.Next() {
+ var groupID, parentGroupID, groupDepth int
+ var groupName string
+ err = rows.Scan(&groupID, &groupName, &parentGroupID, &groupDepth)
+ if err != nil {
+ return false, make([]map[string]interface{}, 0), err
+ }
+ groupInfo := map[string]interface{}{
+ "groupID": groupID,
+ "groupName": groupName,
+ "groupDepth": groupDepth,
+ "parentGroupID": parentGroupID,
}
- return true, groupList, nil
+ groupList = append(groupList, groupInfo)
}
+ return true, groupList, nil
}
-// 更新接口分组脚本
-func UpdateApiGroupScript() bool {
+// UpdateAPIGroupScript 更新接口分组脚本
+func UpdateAPIGroupScript() bool {
db := database2.GetConnection()
// 获取一级分组
sql := "SELECT groupID,groupName,parentGroupID FROM goku_gateway_api_group WHERE isChild = ?;"
@@ -220,86 +219,78 @@ func UpdateApiGroupScript() bool {
//获取记录列
if _, err = rows.Columns(); err != nil {
return false
- } else {
- groupList := make([]map[string]interface{}, 0)
- for rows.Next() {
- var groupID, parentGroupID int
- var groupName, groupPath string
- err = rows.Scan(&groupID, &groupName, &parentGroupID)
+ }
+ groupList := make([]map[string]interface{}, 0)
+ for rows.Next() {
+ var groupID, parentGroupID int
+ var groupName, groupPath string
+ err = rows.Scan(&groupID, &groupName, &parentGroupID)
+ if err != nil {
+ return false
+ }
+ sql = "SELECT groupID,groupName,parentGroupID FROM goku_gateway_api_group WHERE isChild = ? AND parentGroupID = ?;"
+ r, err := db.Query(sql, 1, groupID)
+ if err != nil {
+ return false
+ }
+ groupPath = strconv.Itoa(groupID)
+ defer r.Close()
+
+ for r.Next() {
+ var childGroupID, childParentGroupID int
+ var childGroupName, childGroupPath string
+ err = r.Scan(&childGroupID, &childGroupName, &childParentGroupID)
if err != nil {
return false
}
+ childGroupPath = groupPath + "," + strconv.Itoa(childGroupID)
sql = "SELECT groupID,groupName,parentGroupID FROM goku_gateway_api_group WHERE isChild = ? AND parentGroupID = ?;"
- r, err := db.Query(sql, 1, groupID)
+ rw, err := db.Query(sql, 2, childGroupID)
if err != nil {
return false
}
- groupPath = strconv.Itoa(groupID)
- defer r.Close()
- if _, err = r.Columns(); err != nil {
- return false
- } else {
- for r.Next() {
- var childGroupID, childParentGroupID int
- var childGroupName, childGroupPath string
- err = r.Scan(&childGroupID, &childGroupName, &childParentGroupID)
- if err != nil {
- return false
- }
- childGroupPath = groupPath + "," + strconv.Itoa(childGroupID)
- sql = "SELECT groupID,groupName,parentGroupID FROM goku_gateway_api_group WHERE isChild = ? AND parentGroupID = ?;"
- rw, err := db.Query(sql, 2, childGroupID)
- if err != nil {
- return false
- }
- defer rw.Close()
- if _, err = rw.Columns(); err != nil {
- return false
- } else {
- for rw.Next() {
- var secChildGroupID, secChildParentGroupID int
- var secChildGroupName, secChildGroupPath string
- err = rw.Scan(&secChildGroupID, &secChildGroupName, &secChildParentGroupID)
- if err != nil {
- return false
- }
- secChildGroupPath = childGroupPath + "," + strconv.Itoa(secChildGroupID)
- groupList = append(groupList, map[string]interface{}{
- "groupID": secChildGroupID,
- "groupName": secChildGroupName,
- "groupDepth": 3,
- "parentGroupID": secChildParentGroupID,
- "groupPath": secChildGroupPath,
- })
- }
- }
- groupList = append(groupList, map[string]interface{}{
- "groupID": childGroupID,
- "groupName": childGroupName,
- "groupDepth": 2,
- "parentGroupID": childParentGroupID,
- "groupPath": childGroupPath,
- })
+ defer rw.Close()
+ for rw.Next() {
+ var secChildGroupID, secChildParentGroupID int
+ var secChildGroupName, secChildGroupPath string
+ err = rw.Scan(&secChildGroupID, &secChildGroupName, &secChildParentGroupID)
+ if err != nil {
+ return false
}
+ secChildGroupPath = childGroupPath + "," + strconv.Itoa(secChildGroupID)
+ groupList = append(groupList, map[string]interface{}{
+ "groupID": secChildGroupID,
+ "groupName": secChildGroupName,
+ "groupDepth": 3,
+ "parentGroupID": secChildParentGroupID,
+ "groupPath": secChildGroupPath,
+ })
}
- groupInfo := map[string]interface{}{
- "groupID": groupID,
- "groupName": groupName,
- "groupDepth": 1,
- "parentGroupID": parentGroupID,
- "groupPath": groupPath,
- }
- groupList = append(groupList, groupInfo)
+ groupList = append(groupList, map[string]interface{}{
+ "groupID": childGroupID,
+ "groupName": childGroupName,
+ "groupDepth": 2,
+ "parentGroupID": childParentGroupID,
+ "groupPath": childGroupPath,
+ })
}
- Tx, _ := db.Begin()
- for _, groupInfo := range groupList {
- _, err = Tx.Exec("UPDATE goku_gateway_api_group SET groupPath = ?,groupDepth =? WHERE groupID = ?;", groupInfo["groupPath"].(string), groupInfo["groupDepth"].(int), groupInfo["groupID"].(int))
- if err != nil {
- Tx.Rollback()
+ groupInfo := map[string]interface{}{
+ "groupID": groupID,
+ "groupName": groupName,
+ "groupDepth": 1,
+ "parentGroupID": parentGroupID,
+ "groupPath": groupPath,
+ }
+ groupList = append(groupList, groupInfo)
+ }
+ Tx, _ := db.Begin()
+ for _, groupInfo := range groupList {
+ _, err = Tx.Exec("UPDATE goku_gateway_api_group SET groupPath = ?,groupDepth =? WHERE groupID = ?;", groupInfo["groupPath"].(string), groupInfo["groupDepth"].(int), groupInfo["groupID"].(int))
+ if err != nil {
+ Tx.Rollback()
- }
}
- Tx.Commit()
- return true
}
+ Tx.Commit()
+ return true
}
diff --git a/server/dao/console-mysql/apiPlugin.go b/server/dao/console-mysql/apiPlugin.go
index ed19498..58b860e 100644
--- a/server/dao/console-mysql/apiPlugin.go
+++ b/server/dao/console-mysql/apiPlugin.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
SQL "database/sql"
@@ -15,8 +15,8 @@ import (
var apiPlugins = []string{"goku-proxy_caching", "goku-circuit_breaker"}
-// 新增插件到接口
-func AddPluginToApi(pluginName, config, strategyID string, apiID, userID int) (bool, interface{}, error) {
+// AddPluginToAPI 新增插件到接口
+func AddPluginToAPI(pluginName, config, strategyID string, apiID, userID int) (bool, interface{}, error) {
db := database2.GetConnection()
// 查询接口是否添加该插件
sql := "SELECT apiID FROM goku_conn_plugin_api WHERE strategyID = ? AND pluginName = ? AND apiID = ?;"
@@ -43,8 +43,8 @@ func AddPluginToApi(pluginName, config, strategyID string, apiID, userID int) (b
return true, int(connID), nil
}
-// 修改接口插件配置
-func EditApiPluginConfig(pluginName, config, strategyID string, apiID, userID int) (bool, interface{}, error) {
+// EditAPIPluginConfig 修改接口插件配置
+func EditAPIPluginConfig(pluginName, config, strategyID string, apiID, userID int) (bool, interface{}, error) {
db := database2.GetConnection()
// 查询接口是否添加该插件
t := time.Now()
@@ -74,7 +74,8 @@ func EditApiPluginConfig(pluginName, config, strategyID string, apiID, userID in
return true, id, nil
}
-func GetApiPluginList(apiID int, strategyID string) (bool, []map[string]interface{}, error) {
+//GetAPIPluginList 获取接口插件列表
+func GetAPIPluginList(apiID int, strategyID string) (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
sql := `SELECT goku_conn_plugin_api.connID,goku_conn_plugin_api.pluginName,IFNULL(goku_conn_plugin_api.createTime,""),IFNULL(goku_conn_plugin_api.updateTime,""),goku_conn_plugin_api.pluginConfig,goku_plugin.pluginPriority, IF(goku_plugin.pluginStatus=0,-1,goku_conn_plugin_api.pluginStatus) as pluginStatus,goku_gateway_api.requestURL FROM goku_conn_plugin_api INNER JOIN goku_plugin ON goku_plugin.pluginName = goku_conn_plugin_api.pluginName INNER goku_gateway_api.apiID = goku_conn_plugin_api.apiID WHERE goku_conn_plugin_api.apiID = ? AND goku_conn_plugin_api.strategyID = ? ORDER BY pluginStatus DESC,goku_conn_plugin_api.updateTime DESC;`
rows, err := db.Query(sql, apiID, strategyID)
@@ -84,34 +85,30 @@ func GetApiPluginList(apiID int, strategyID string) (bool, []map[string]interfac
defer rows.Close()
pluginList := make([]map[string]interface{}, 0)
//获取记录列
- if _, err = rows.Columns(); err != nil {
- return false, nil, err
- } else {
- for rows.Next() {
- var pluginPriority, pluginStatus, connID int
- var pluginName, pluginConfig, createTime, updateTime, requestURL string
- err = rows.Scan(&connID, &pluginName, &pluginConfig, &createTime, &updateTime, &pluginPriority, &pluginStatus, &requestURL)
- if err != nil {
- info := err.Error()
- log.Info(info)
- }
- pluginInfo := map[string]interface{}{
- "connID": connID,
- "pluginName": pluginName,
- "pluginConfig": pluginConfig,
- "pluginPriority": pluginPriority,
- "pluginStatus": pluginStatus,
- "createTime": createTime,
- "updateTime": updateTime,
- "requestURL": requestURL,
- }
- pluginList = append(pluginList, pluginInfo)
+ for rows.Next() {
+ var pluginPriority, pluginStatus, connID int
+ var pluginName, pluginConfig, createTime, updateTime, requestURL string
+ err = rows.Scan(&connID, &pluginName, &pluginConfig, &createTime, &updateTime, &pluginPriority, &pluginStatus, &requestURL)
+ if err != nil {
+ info := err.Error()
+ log.Info(info)
+ }
+ pluginInfo := map[string]interface{}{
+ "connID": connID,
+ "pluginName": pluginName,
+ "pluginConfig": pluginConfig,
+ "pluginPriority": pluginPriority,
+ "pluginStatus": pluginStatus,
+ "createTime": createTime,
+ "updateTime": updateTime,
+ "requestURL": requestURL,
}
- return true, pluginList, nil
+ pluginList = append(pluginList, pluginInfo)
}
+ return true, pluginList, nil
}
-// 获取插件优先级
+// GetPluginIndex 获取插件优先级
func GetPluginIndex(pluginName string) (bool, int, error) {
db := database2.GetConnection()
var pluginPriority int
@@ -123,8 +120,8 @@ func GetPluginIndex(pluginName string) (bool, int, error) {
return true, pluginPriority, nil
}
-// 通过ApiID获取配置信息
-func GetApiPluginConfig(apiID int, strategyID, pluginName string) (bool, map[string]string, error) {
+// GetAPIPluginConfig 通过APIID获取配置信息
+func GetAPIPluginConfig(apiID int, strategyID, pluginName string) (bool, map[string]string, error) {
db := database2.GetConnection()
sql := "SELECT goku_gateway_api.apiName,goku_gateway_api.requestURL,goku_conn_plugin_api.pluginConfig FROM goku_conn_plugin_api INNER JOIN goku_gateway_api ON goku_gateway_api.apiID = goku_conn_plugin_api.apiID WHERE goku_conn_plugin_api.apiID = ? AND goku_conn_plugin_api.strategyID = ? AND goku_conn_plugin_api.pluginName = ?;"
var p, apiName, requestURL string
@@ -132,31 +129,28 @@ func GetApiPluginConfig(apiID int, strategyID, pluginName string) (bool, map[str
if err != nil {
if err == SQL.ErrNoRows {
return false, nil, errors.New("[ERROR]Can not find the plugin")
- } else {
- return false, nil, err
}
+ return false, nil, err
- } else {
- apiPluginInfo := map[string]string{
- "pluginConfig": p,
- "apiName": apiName,
- "requestURL": requestURL,
- }
- return true, apiPluginInfo, nil
}
+ apiPluginInfo := map[string]string{
+ "pluginConfig": p,
+ "apiName": apiName,
+ "requestURL": requestURL,
+ }
+ return true, apiPluginInfo, nil
}
-// 检查策略组是否绑定插件
-func CheckPluginIsExistInApi(strategyID, pluginName string, apiID int) (bool, error) {
+// CheckPluginIsExistInAPI 检查策略组是否绑定插件
+func CheckPluginIsExistInAPI(strategyID, pluginName string, apiID int) (bool, error) {
db := database2.GetConnection()
sql := "SELECT apiID FROM goku_conn_plugin_api WHERE strategyID = ? AND pluginName = ? AND apiID = ?;"
var id int
err := db.QueryRow(sql, strategyID, pluginName, apiID).Scan(&id)
if err != nil {
return false, err
- } else {
- return true, err
}
+ return true, err
}
// GetAPIPluginInStrategyByAPIID 通过接口ID获取策略组中接口插件列表
@@ -230,8 +224,8 @@ func GetAPIPluginInStrategyByAPIID(strategyID string, apiID int, keyword string,
return true, pluginList, apiInfo, nil
}
-// 获取策略组中所有接口插件列表
-func GetAllApiPluginInStrategy(strategyID string) (bool, []map[string]interface{}, error) {
+// GetAllAPIPluginInStrategy 获取策略组中所有接口插件列表
+func GetAllAPIPluginInStrategy(strategyID string) (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
sql := `SELECT goku_conn_plugin_api.connID,goku_conn_plugin_api.apiID,goku_gateway_api.apiName,goku_gateway_api.requestURL,goku_conn_plugin_api.pluginName,IFNULL(goku_conn_plugin_api.createTime,""),IFNULL(goku_conn_plugin_api.updateTime,""),IF(goku_plugin.pluginStatus=0,-1,goku_conn_plugin_api.pluginStatus) as pluginStatus,IFNULL(goku_plugin.pluginDesc,"") FROM goku_conn_plugin_api INNER JOIN goku_gateway_api ON goku_gateway_api.apiID = goku_conn_plugin_api.apiID INNER JOIN goku_plugin ON goku_plugin.pluginName = goku_conn_plugin_api.pluginName WHERE goku_conn_plugin_api.strategyID = ? ORDER BY pluginStatus DESC,goku_conn_plugin_api.updateTime DESC;`
rows, err := db.Query(sql, strategyID)
@@ -241,35 +235,31 @@ func GetAllApiPluginInStrategy(strategyID string) (bool, []map[string]interface{
defer rows.Close()
pluginList := make([]map[string]interface{}, 0)
//获取记录列
- if _, err = rows.Columns(); err != nil {
- return false, make([]map[string]interface{}, 0), err
- } else {
- for rows.Next() {
- var pluginStatus, apiID, connID int
- var apiName, pluginName, pluginDesc, createTime, updateTime, requestURL string
- err = rows.Scan(&connID, &apiID, &apiName, &requestURL, &pluginName, &createTime, &updateTime, &pluginStatus, &pluginDesc)
- if err != nil {
- return false, make([]map[string]interface{}, 0), err
- }
- pluginInfo := map[string]interface{}{
- "connID": connID,
- "apiID": apiID,
- "apiName": apiName,
- "pluginName": pluginName,
- "pluginStatus": pluginStatus,
- "createTime": createTime,
- "updateTime": updateTime,
- "requestURL": requestURL,
- "pluginDesc": pluginDesc,
- }
- pluginList = append(pluginList, pluginInfo)
+ for rows.Next() {
+ var pluginStatus, apiID, connID int
+ var apiName, pluginName, pluginDesc, createTime, updateTime, requestURL string
+ err = rows.Scan(&connID, &apiID, &apiName, &requestURL, &pluginName, &createTime, &updateTime, &pluginStatus, &pluginDesc)
+ if err != nil {
+ return false, make([]map[string]interface{}, 0), err
}
- return true, pluginList, nil
+ pluginInfo := map[string]interface{}{
+ "connID": connID,
+ "apiID": apiID,
+ "apiName": apiName,
+ "pluginName": pluginName,
+ "pluginStatus": pluginStatus,
+ "createTime": createTime,
+ "updateTime": updateTime,
+ "requestURL": requestURL,
+ "pluginDesc": pluginDesc,
+ }
+ pluginList = append(pluginList, pluginInfo)
}
+ return true, pluginList, nil
}
-// 批量修改策略组插件状态
-func BatchEditApiPluginStatus(connIDList, strategyID string, pluginStatus, userID int) (bool, string, error) {
+// BatchEditAPIPluginStatus 批量修改策略组插件状态
+func BatchEditAPIPluginStatus(connIDList, strategyID string, pluginStatus, userID int) (bool, string, error) {
db := database2.GetConnection()
t := time.Now()
now := t.Format("2006-01-02 15:04:05")
@@ -291,31 +281,26 @@ func BatchEditApiPluginStatus(connIDList, strategyID string, pluginStatus, userI
}
defer rows.Close()
//获取记录列
- if _, err = rows.Columns(); err != nil {
- Tx.Rollback()
- return false, "[ERROR]Fail to get data!", err
- } else {
- for rows.Next() {
- var apiID int
- err = rows.Scan(&apiID)
- if err != nil {
- Tx.Rollback()
- return false, "[ERROR]Fail to get data!", err
- }
- }
- sql = "UPDATE goku_gateway_strategy SET updateTime = ? WHERE strategyID = ?;"
- _, err = Tx.Exec(sql, now, strategyID)
+ for rows.Next() {
+ var apiID int
+ err = rows.Scan(&apiID)
if err != nil {
Tx.Rollback()
- return false, "[ERROR]Fail to update data!", err
+ return false, "[ERROR]Fail to get data!", err
}
- Tx.Commit()
}
+ sql = "UPDATE goku_gateway_strategy SET updateTime = ? WHERE strategyID = ?;"
+ _, err = Tx.Exec(sql, now, strategyID)
+ if err != nil {
+ Tx.Rollback()
+ return false, "[ERROR]Fail to update data!", err
+ }
+ Tx.Commit()
return true, "", nil
}
-// 批量删除策略组插件
-func BatchDeleteApiPlugin(connIDList, strategyID string) (bool, string, error) {
+// BatchDeleteAPIPlugin 批量删除策略组插件
+func BatchDeleteAPIPlugin(connIDList, strategyID string) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
Tx, _ := db.Begin()
@@ -329,19 +314,14 @@ func BatchDeleteApiPlugin(connIDList, strategyID string) (bool, string, error) {
}
defer rows.Close()
//获取记录列
- if _, err = rows.Columns(); err != nil {
- Tx.Rollback()
- return false, "[ERROR]Fail to get data!", err
- } else {
- for rows.Next() {
- var apiID int
- err = rows.Scan(&apiID)
- if err != nil {
- Tx.Rollback()
- return false, "[ERROR]Fail to get data!", err
- }
- apiIDList = append(apiIDList, apiID)
+ for rows.Next() {
+ var apiID int
+ err = rows.Scan(&apiID)
+ if err != nil {
+ Tx.Rollback()
+ return false, "[ERROR]Fail to get data!", err
}
+ apiIDList = append(apiIDList, apiID)
}
sql = "DELETE FROM goku_conn_plugin_api WHERE connID IN (" + connIDList + ");"
_, err = Tx.Exec(sql)
@@ -360,8 +340,8 @@ func BatchDeleteApiPlugin(connIDList, strategyID string) (bool, string, error) {
return true, "", nil
}
-// 通过connID获取插件名称
-func GetApiPluginName(connID int) (bool, string, error) {
+// GetAPIPluginName 通过connID获取插件名称
+func GetAPIPluginName(connID int) (bool, string, error) {
db := database2.GetConnection()
var pluginName string
sql := "SELECT pluginName FROM goku_conn_plugin_api WHERE connID = ?"
@@ -372,8 +352,8 @@ func GetApiPluginName(connID int) (bool, string, error) {
return true, "", nil
}
-// 通过connIDList判断插件是否存在
-func CheckApiPluginIsExistByConnIDList(connIDList, pluginName string) (bool, []int, error) {
+// CheckAPIPluginIsExistByConnIDList 通过connIDList判断插件是否存在
+func CheckAPIPluginIsExistByConnIDList(connIDList, pluginName string) (bool, []int, error) {
db := database2.GetConnection()
sql := "SELECT apiID FROM goku_conn_plugin_api WHERE connID IN (" + connIDList + ") AND pluginName = ?;"
rows, err := db.Query(sql, pluginName)
@@ -382,23 +362,20 @@ func CheckApiPluginIsExistByConnIDList(connIDList, pluginName string) (bool, []i
}
defer rows.Close()
apiIDList := make([]int, 0)
- if _, err = rows.Columns(); err != nil {
- return false, make([]int, 0), err
- } else {
- for rows.Next() {
- var apiID int
- err = rows.Scan(&apiID)
- if err != nil {
- return false, make([]int, 0), err
- }
- apiIDList = append(apiIDList, apiID)
+
+ for rows.Next() {
+ var apiID int
+ err = rows.Scan(&apiID)
+ if err != nil {
+ return false, make([]int, 0), err
}
+ apiIDList = append(apiIDList, apiID)
}
return true, apiIDList, nil
}
-// 获取没有绑定嵌套插件列表
-func GetApiPluginListWithNotAssignApiList(strategyID string) (bool, []map[string]interface{}, error) {
+// GetAPIPluginListWithNotAssignAPIList 获取没有绑定嵌套插件列表
+func GetAPIPluginListWithNotAssignAPIList(strategyID string) (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
sql := "SELECT pluginID,pluginDesc,pluginName FROM goku_plugin WHERE pluginType = 2 AND pluginStatus = 1;"
rows, err := db.Query(sql)
@@ -408,55 +385,52 @@ func GetApiPluginListWithNotAssignApiList(strategyID string) (bool, []map[string
defer rows.Close()
pluginList := make([]map[string]interface{}, 0)
//获取记录列
- if _, err = rows.Columns(); err != nil {
- return false, make([]map[string]interface{}, 0), err
- } else {
- sql = "SELECT goku_gateway_api.apiID,goku_gateway_api.apiName,goku_gateway_api.requestURL FROM goku_gateway_api INNER JOIN goku_conn_strategy_api ON goku_gateway_api.apiID = goku_conn_strategy_api.apiID WHERE goku_conn_strategy_api.strategyID = ? AND goku_gateway_api.apiID NOT IN (SELECT goku_conn_plugin_api.apiID FROM goku_conn_plugin_api WHERE goku_conn_plugin_api.strategyID = ? AND goku_conn_plugin_api.pluginName = ?);"
- for rows.Next() {
- var pluginID int
- var pluginName, chineseName string
- err = rows.Scan(&pluginID, &chineseName, &pluginName)
- if err != nil {
- info := err.Error()
- log.Info(info)
- return false, make([]map[string]interface{}, 0), err
- }
- r, err := db.Query(sql, strategyID, strategyID, pluginName)
+ sql = "SELECT goku_gateway_api.apiID,goku_gateway_api.apiName,goku_gateway_api.requestURL FROM goku_gateway_api INNER JOIN goku_conn_strategy_api ON goku_gateway_api.apiID = goku_conn_strategy_api.apiID WHERE goku_conn_strategy_api.strategyID = ? AND goku_gateway_api.apiID NOT IN (SELECT goku_conn_plugin_api.apiID FROM goku_conn_plugin_api WHERE goku_conn_plugin_api.strategyID = ? AND goku_conn_plugin_api.pluginName = ?);"
+ for rows.Next() {
+ var pluginID int
+ var pluginName, chineseName string
+ err = rows.Scan(&pluginID, &chineseName, &pluginName)
+ if err != nil {
+ info := err.Error()
+ log.Info(info)
+ return false, make([]map[string]interface{}, 0), err
+ }
+ r, err := db.Query(sql, strategyID, strategyID, pluginName)
+ if err != nil {
+ return false, make([]map[string]interface{}, 0), err
+ }
+ defer r.Close()
+ apiList := make([]map[string]interface{}, 0)
+ for r.Next() {
+ var (
+ apiID int
+ apiName string
+ requestURL string
+ )
+ err = r.Scan(&apiID, &apiName, &requestURL)
if err != nil {
return false, make([]map[string]interface{}, 0), err
}
- defer r.Close()
- apiList := make([]map[string]interface{}, 0)
- for r.Next() {
- var (
- apiID int
- apiName string
- requestURL string
- )
- err = r.Scan(&apiID, &apiName, &requestURL)
- if err != nil {
- return false, make([]map[string]interface{}, 0), err
- }
- apiList = append(apiList, map[string]interface{}{
- "apiID": apiID,
- "apiName": apiName,
- "requestURL": requestURL,
- })
+ apiList = append(apiList, map[string]interface{}{
+ "apiID": apiID,
+ "apiName": apiName,
+ "requestURL": requestURL,
+ })
- }
- pluginInfo := map[string]interface{}{
- "chineseName": chineseName,
- "pluginName": pluginName,
- "pluginID": pluginID,
- "apiList": apiList,
- }
- pluginList = append(pluginList, pluginInfo)
}
- return true, pluginList, nil
+ pluginInfo := map[string]interface{}{
+ "chineseName": chineseName,
+ "pluginName": pluginName,
+ "pluginID": pluginID,
+ "apiList": apiList,
+ }
+ pluginList = append(pluginList, pluginInfo)
}
+ return true, pluginList, nil
}
-func BatchUpdateApiPluginUpdateTag(strategyIDList string) error {
+//BatchUpdateAPIPluginUpdateTag 批量更新插件更新标识
+func BatchUpdateAPIPluginUpdateTag(strategyIDList string) error {
db := database2.GetConnection()
code := make([]string, 0, len(apiPlugins))
strategyIDs := strings.Split(strategyIDList, ",")
@@ -481,7 +455,8 @@ func BatchUpdateApiPluginUpdateTag(strategyIDList string) error {
return nil
}
-func UpdateApiTagByPluginName(strategyID string, apiIDList string, pluginList string) error {
+//UpdateAPITagByPluginName 通过插件名称更新接口插件标识
+func UpdateAPITagByPluginName(strategyID string, apiIDList string, pluginList string) error {
db := database2.GetConnection()
plugins := strings.Split(pluginList, ",")
code := make([]string, 0, len(plugins))
@@ -501,19 +476,12 @@ func UpdateApiTagByPluginName(strategyID string, apiIDList string, pluginList st
return nil
}
-func UpdateAllApiPluginUpdateTag() error {
+//UpdateAllAPIPluginUpdateTag 更新所有接口插件更新标识
+func UpdateAllAPIPluginUpdateTag() error {
db := database2.GetConnection()
- // code := make([]string, 0, len(apiPlugins))
updateTag := time.Now().Format("20060102150405")
- // s := make([]interface{}, 0, len(apiPlugins)+1)
- // s = append(s, updateTag)
- // for i := 0; i < len(apiPlugins); i++ {
- // code = append(code, "?")
- // s = append(s, apiPlugins[i])
- // }
- // sql := "UPDATE goku_conn_plugin_api SET updateTag = ? WHERE pluginName IN (" + strings.Join(code, ",") + ");"
+ // s := make([]interface{}
sql := "UPDATE goku_conn_plugin_api SET updateTag = ?;"
- // _, err := db.Exec(sql, s...)
_, err := db.Exec(sql, updateTag)
if err != nil {
return err
diff --git a/server/dao/console-mysql/apiStrategy.go b/server/dao/console-mysql/apiStrategy.go
index 8b52cff..4238c7f 100644
--- a/server/dao/console-mysql/apiStrategy.go
+++ b/server/dao/console-mysql/apiStrategy.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
"fmt"
@@ -9,8 +9,8 @@ import (
database2 "github.com/eolinker/goku-api-gateway/common/database"
)
-// 将接口加入策略组
-func AddApiToStrategy(apiList []string, strategyID string) (bool, string, error) {
+// AddAPIToStrategy 将接口加入策略组
+func AddAPIToStrategy(apiList []string, strategyID string) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
sql2 := "SELECT apiID FROM goku_conn_strategy_api WHERE apiID = ? AND strategyID = ?"
@@ -56,8 +56,8 @@ func AddApiToStrategy(apiList []string, strategyID string) (bool, string, error)
return true, "", nil
}
-// SetApiTargetOfStrategy 重定向接口负载
-func SetApiTargetOfStrategy(apiId int, strategyID string, target string) (bool, string, error) {
+// SetAPITargetOfStrategy 重定向接口负载
+func SetAPITargetOfStrategy(apiID int, strategyID string, target string) (bool, string, error) {
db := database2.GetConnection()
sql := "UPDATE goku_conn_strategy_api SET `target` = ? where apiID = ? AND strategyID = ? "
stmt, err := db.Prepare(sql)
@@ -65,7 +65,7 @@ func SetApiTargetOfStrategy(apiId int, strategyID string, target string) (bool,
return false, err.Error(), err
}
- _, e := stmt.Exec(target, apiId, strategyID)
+ _, e := stmt.Exec(target, apiID, strategyID)
if e != nil {
return false, e.Error(), e
@@ -74,8 +74,8 @@ func SetApiTargetOfStrategy(apiId int, strategyID string, target string) (bool,
return true, "", nil
}
-// BatchSetApiTargetOfStrategy 批量重定向接口负载
-func BatchSetApiTargetOfStrategy(apiIds []int, strategyID string, target string) (bool, string, error) {
+// BatchSetAPITargetOfStrategy 批量重定向接口负载
+func BatchSetAPITargetOfStrategy(apiIds []int, strategyID string, target string) (bool, string, error) {
idLen := len(apiIds)
s := make([]interface{}, 0, idLen+2)
c := ""
@@ -286,8 +286,8 @@ func GetAPIListFromStrategy(strategyID, keyword string, condition, page, pageSiz
return true, apiList, count, nil
}
-// CheckIsExistApiInStrategy 检查插件是否添加进策略组
-func CheckIsExistApiInStrategy(apiID int, strategyID string) (bool, string, error) {
+// CheckIsExistAPIInStrategy 检查插件是否添加进策略组
+func CheckIsExistAPIInStrategy(apiID int, strategyID string) (bool, string, error) {
db := database2.GetConnection()
var id int
sql := "SELECT connID FROM goku_conn_strategy_api WHERE apiID = ? AND strategyID = ?"
@@ -319,7 +319,7 @@ func getSimpleAPIListInStrategy(strategyID string, projectID int) map[string]str
return simpleMap
}
-// GetAPIIDListNotInStrategyByProject 获取未被该策略组绑定的接口ID列表(通过项目)
+// GetAPIIDListNotInStrategy 获取未被该策略组绑定的接口ID列表(通过项目)
func GetAPIIDListNotInStrategy(strategyID string, projectID, groupID int, keyword string) (bool, []int, error) {
requestMap := getSimpleAPIListInStrategy(strategyID, projectID)
rule := make([]string, 0, 3)
@@ -376,22 +376,21 @@ func getAPIGroupRule(projectID, groupID int) (string, error) {
return groupRule, nil
}
return "", nil
- } else {
- var groupPath string
- sql := "SELECT groupPath FROM goku_gateway_api_group WHERE groupID = ?;"
- err := db.QueryRow(sql, groupID).Scan(&groupPath)
- if err != nil {
- return "", err
- }
- // 获取分组ID列表
- sql = "SELECT GROUP_CONCAT(DISTINCT groupID) AS groupID FROM goku_gateway_api_group WHERE projectID = ? AND groupPath LIKE ?;"
- groupIDList := ""
- err = db.QueryRow(sql, projectID, groupPath+"%").Scan(&groupIDList)
- if err != nil {
- return "", err
- }
- return fmt.Sprintf("A.groupID IN (%s)", groupIDList), nil
}
+ var groupPath string
+ sql := "SELECT groupPath FROM goku_gateway_api_group WHERE groupID = ?;"
+ err := db.QueryRow(sql, groupID).Scan(&groupPath)
+ if err != nil {
+ return "", err
+ }
+ // 获取分组ID列表
+ sql = "SELECT GROUP_CONCAT(DISTINCT groupID) AS groupID FROM goku_gateway_api_group WHERE projectID = ? AND groupPath LIKE ?;"
+ groupIDList := ""
+ err = db.QueryRow(sql, projectID, groupPath+"%").Scan(&groupIDList)
+ if err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("A.groupID IN (%s)", groupIDList), nil
}
// GetAPIListNotInStrategy 获取未被该策略组绑定的接口列表(通过项目)
@@ -438,7 +437,7 @@ func GetAPIListNotInStrategy(strategyID string, projectID, groupID, page, pageSi
}
if value, ok := requestMap[requestURL]; ok {
if strings.Contains(strings.ToUpper(value), strings.ToUpper(requestMethod)) {
- count -= 1
+ count = count - 1
continue
}
}
@@ -459,8 +458,8 @@ func GetAPIListNotInStrategy(strategyID string, projectID, groupID, page, pageSi
return true, apiList, count, nil
}
-// 批量删除策略组接口
-func BatchDeleteApiInStrategy(apiIDList, strategyID string) (bool, string, error) {
+// BatchDeleteAPIInStrategy 批量删除策略组接口
+func BatchDeleteAPIInStrategy(apiIDList, strategyID string) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
Tx, _ := db.Begin()
diff --git a/server/dao/console-mysql/auth.go b/server/dao/console-mysql/auth.go
index 7363065..9a9a662 100644
--- a/server/dao/console-mysql/auth.go
+++ b/server/dao/console-mysql/auth.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
"encoding/json"
@@ -16,6 +16,7 @@ type basicAuthConf struct {
Remark string `json:"remark"`
}
+//APIKeyConf apiKey配置
type APIKeyConf struct {
APIKey string `json:"Apikey"`
TokenPlace string `json:"tokenPlace"`
@@ -23,6 +24,7 @@ type APIKeyConf struct {
Remark string `json:"remark"`
}
+//OAuth2GlobalConf oauth2全局配置
type OAuth2GlobalConf struct {
oauth2Conf
Oauth2CredentialList []*oauth2Credential `json:"oauth2CredentialList"`
@@ -36,7 +38,7 @@ type oauth2Conf struct {
EnableImplicitGrant bool `json:"enableImplicitGrant"` //enable_implicit_grant = { required = true, type = "boolean", default = false },
EnableClientCredentials bool `json:"enableClientCredentials"` //enable_client_credentials = { required = true, type = "boolean", default = false },
HideCredentials bool `json:"hideCredentials"` //hide_credentials = { type = "boolean", default = false },
- AcceptHttpIfAlreadyTerminated bool `json:"acceptHttpIfAlreadyTerminated"` //accept_http_if_already_terminated = { required = false, type = "boolean", default = false },
+ AcceptHTTPIfAlreadyTerminated bool `json:"acceptHttpIfAlreadyTerminated"` //accept_http_if_already_terminated = { required = false, type = "boolean", default = false },
RefreshTokenTTL int `json:"refreshTokenTTL"` //refresh_token_ttl = {required = true, type = "number", default = 1209600} -- original hardcoded value - 14 days
}
@@ -64,7 +66,7 @@ type oauth2Credential struct {
Remark string `json:"remark"`
}
-// 获取认证信息
+// GetAuthStatus 获取鉴权状态信息
func GetAuthStatus(strategyID string) (bool, map[string]interface{}, error) {
db := database2.GetConnection()
var basicStatus, apikeyStatus, jwtStatus, oAuthStatus int
@@ -97,7 +99,7 @@ func GetAuthStatus(strategyID string) (bool, map[string]interface{}, error) {
return true, authInfo, err
}
-// 获取认证信息
+// GetAuthInfo 获取认证信息
func GetAuthInfo(strategyID string) (bool, map[string]interface{}, error) {
db := database2.GetConnection()
var strategyName, auth string
@@ -169,7 +171,7 @@ func GetAuthInfo(strategyID string) (bool, map[string]interface{}, error) {
return true, authInfo, nil
}
-// 编辑认证信息
+// EditAuthInfo 编辑认证信息
func EditAuthInfo(strategyID, strategyName, basicAuthList, apikeyList, jwtCredentialList, oauth2CredentialList string, delClientIDList []string) (bool, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -227,12 +229,12 @@ func EditAuthInfo(strategyID, strategyName, basicAuthList, apikeyList, jwtCreden
return false, err
}
jwtConf.JwtCredentials = jwtList
- jwtJson, err := json.Marshal(jwtConf)
+ jwtJSON, err := json.Marshal(jwtConf)
if err != nil {
Tx.Rollback()
return false, err
}
- _, err = Tx.Exec("UPDATE goku_conn_plugin_strategy SET pluginConfig = ?,updateTime = ? WHERE strategyID = ? AND pluginName = ? AND pluginStatus = 1 ", jwtJson, now, strategyID, "goku-jwt_auth")
+ _, err = Tx.Exec("UPDATE goku_conn_plugin_strategy SET pluginConfig = ?,updateTime = ? WHERE strategyID = ? AND pluginName = ? AND pluginStatus = 1 ", jwtJSON, now, strategyID, "goku-jwt_auth")
if err != nil {
Tx.Rollback()
return false, err
diff --git a/server/dao/console-mysql/cluster.go b/server/dao/console-mysql/cluster.go
index e60da0a..82b1b4b 100644
--- a/server/dao/console-mysql/cluster.go
+++ b/server/dao/console-mysql/cluster.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
"github.com/eolinker/goku-api-gateway/common/database"
@@ -6,6 +6,7 @@ import (
jsoniter "github.com/json-iterator/go"
)
+//InsertClusters 插入集群信息
func InsertClusters(cs []*entity.ClusterInfo) error {
db := database.GetConnection()
stmt, e := db.Prepare("INSERT INTO `goku_cluster`(`name`,`title`,`note`,`db`,`redis`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `title`=VALUES(`title`),`note`=VALUES(`note`),`db`=VALUES(`db`),`redis`=VALUES(`redis`)")
@@ -20,6 +21,8 @@ func InsertClusters(cs []*entity.ClusterInfo) error {
return nil
}
+
+//LoadClusters 加载集群列表
func LoadClusters() (map[string]*entity.ClusterInfo, error) {
db := database.GetConnection()
sql := "select `id`, `name`,`title`,`note`,`db`,`redis` from `goku_cluster`;"
@@ -38,7 +41,7 @@ func LoadClusters() (map[string]*entity.ClusterInfo, error) {
v := new(entity.ClusterInfo)
db := ""
redis := ""
- err := rows.Scan(&v.Id, &v.Name, &v.Title, &v.Note, &db, &redis)
+ err := rows.Scan(&v.ID, &v.Name, &v.Title, &v.Note, &db, &redis)
if err != nil {
return nil, nil
}
diff --git a/server/dao/console-mysql/gateway.go b/server/dao/console-mysql/gateway.go
index dba9aca..16c6bf0 100644
--- a/server/dao/console-mysql/gateway.go
+++ b/server/dao/console-mysql/gateway.go
@@ -1,9 +1,10 @@
-package console_mysql
+package consolemysql
import (
database2 "github.com/eolinker/goku-api-gateway/common/database"
)
+//GetGatewayConfig 获取网关配置
func GetGatewayConfig() (map[string]interface{}, error) {
db := database2.GetConnection()
var successCode string
@@ -22,7 +23,7 @@ func GetGatewayConfig() (map[string]interface{}, error) {
return gatewayConfig, nil
}
-// 编辑网关基本配置
+// EditGatewayBaseConfig 编辑网关基本配置
func EditGatewayBaseConfig(successCode string, nodeUpdatePeriod, monitorUpdatePeriod, monitorTimeout int) (bool, string, error) {
db := database2.GetConnection()
sql := "SELECT successCode FROM goku_gateway WHERE id = 1;"
@@ -44,7 +45,7 @@ func EditGatewayBaseConfig(successCode string, nodeUpdatePeriod, monitorUpdatePe
return true, "", nil
}
-// 编辑网关告警配置
+// EditGatewayAlarmConfig 编辑网关告警配置
func EditGatewayAlarmConfig(apiAlertInfo, sender, senderPassword, smtpAddress string, alertStatus, smtpPort, smtpProtocol int) (bool, string, error) {
db := database2.GetConnection()
sql := "SELECT successCode FROM goku_gateway WHERE id = 1;"
diff --git a/server/dao/console-mysql/guest.go b/server/dao/console-mysql/guest.go
index 2d45fc0..71197d7 100644
--- a/server/dao/console-mysql/guest.go
+++ b/server/dao/console-mysql/guest.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
SQL "database/sql"
@@ -6,6 +6,7 @@ import (
"github.com/eolinker/goku-api-gateway/utils"
)
+//Login 登录
func Login(loginCall, loginPassword string) (bool, int) {
db := database.GetConnection()
var userID int
@@ -16,7 +17,7 @@ func Login(loginCall, loginPassword string) (bool, int) {
return true, userID
}
-// 检查用户是否登录
+// CheckLogin 检查用户是否登录
func CheckLogin(userToken string, userID int) bool {
db := database.GetConnection()
var loginPassword, loginCall string
@@ -26,12 +27,11 @@ func CheckLogin(userToken string, userID int) bool {
}
if utils.Md5(loginCall+loginPassword) == userToken {
return true
- } else {
- return false
}
+ return false
}
-// 用户注册
+//Register 用户注册
func Register(loginCall, loginPassword string) bool {
db := database.GetConnection()
sql := "SELECT userID,loginPassword FROM goku_admin WHERE loginCall = ?;"
@@ -58,7 +58,6 @@ func Register(loginCall, loginPassword string) bool {
affectRow, _ := rows.RowsAffected()
if affectRow > 0 {
return true
- } else {
- return false
}
+ return false
}
diff --git a/server/dao/console-mysql/import.go b/server/dao/console-mysql/import.go
index 67a5831..4e010d0 100644
--- a/server/dao/console-mysql/import.go
+++ b/server/dao/console-mysql/import.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
SQL "database/sql"
@@ -12,20 +12,18 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-var method []string = []string{"POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"}
+var method = []string{"POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"}
-// 导入分组信息
-func importApiGroupInfo(Tx *SQL.Tx, groupName, groupPath string, parentGroupID, projectID, groupDepth int) (bool, int, string) {
+// importAPIGroupInfo 导入分组信息
+func importAPIGroupInfo(Tx *SQL.Tx, groupName, groupPath string, parentGroupID, projectID, groupDepth int) (bool, int, string) {
result, err := Tx.Exec("INSERT INTO goku_gateway_api_group (projectID,groupName,parentGroupID,groupDepth) VALUES (?,?,?,?);", projectID, groupName, parentGroupID, groupDepth)
if err != nil {
- // Tx.Rollback()
info := err.Error()
log.Info(info)
return false, 0, ""
}
groupID, err := result.LastInsertId()
if err != nil {
- // Tx.Rollback()
info := err.Error()
log.Info(info)
return false, 0, ""
@@ -35,7 +33,6 @@ func importApiGroupInfo(Tx *SQL.Tx, groupName, groupPath string, parentGroupID,
// 更新groupPath
_, err = Tx.Exec("UPDATE goku_gateway_api_group SET groupPath = ? WHERE groupID = ?;", groupPath, id)
if err != nil {
- // Tx.Rollback()
info := err.Error()
log.Info(info)
return false, 0, ""
@@ -43,13 +40,13 @@ func importApiGroupInfo(Tx *SQL.Tx, groupName, groupPath string, parentGroupID,
return true, id, groupPath
}
-// 导入接口信息
-func importApiInfo(Tx *SQL.Tx, api entity.AmsApiInfo, projectID, groupID, userID int) bool {
+// importAPIInfo 导入接口信息
+func importAPIInfo(Tx *SQL.Tx, api entity.AmsAPIInfo, projectID, groupID, userID int) bool {
// 新增API
requestURL := ""
host := ""
protocol := "http"
- u, err := url.ParseRequestURI(api.BaseInfo.ApiURI)
+ u, err := url.ParseRequestURI(api.BaseInfo.APIURI)
if err == nil {
requestURL = u.Path
if u.Scheme != "" {
@@ -59,23 +56,22 @@ func importApiInfo(Tx *SQL.Tx, api entity.AmsApiInfo, projectID, groupID, userID
}
}
} else {
- requestURL = api.BaseInfo.ApiURI
+ requestURL = api.BaseInfo.APIURI
}
stripSlash := true
log.Debug(protocol, host, stripSlash)
now := time.Now().Format("2006-01-02 15:04:05")
- requestMethod := method[api.BaseInfo.ApiRequestType]
- _, err = Tx.Exec("INSERT INTO goku_gateway_api (projectID,groupID,apiName,requestURL,targetURL,requestMethod,targetMethod,isFollow,stripPrefix,timeout,retryCount,createTime,updateTime,managerID,lastUpdateUserID,createUserID,protocol,balanceName,stripSlash) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);", projectID, groupID, api.BaseInfo.ApiName, requestURL, requestURL, requestMethod, requestMethod, "true", "true", 2000, 0, now, now, userID, userID, userID, protocol, host, stripSlash)
+ requestMethod := method[api.BaseInfo.APIRequestType]
+ _, err = Tx.Exec("INSERT INTO goku_gateway_api (projectID,groupID,apiName,requestURL,targetURL,requestMethod,targetMethod,isFollow,stripPrefix,timeout,retryCount,createTime,updateTime,managerID,lastUpdateUserID,createUserID,protocol,balanceName,stripSlash) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);", projectID, groupID, api.BaseInfo.APIName, requestURL, requestURL, requestMethod, requestMethod, "true", "true", 2000, 0, now, now, userID, userID, userID, protocol, host, stripSlash)
if err != nil {
- // Tx.Rollback()
-
log.Error(err)
return false
}
return true
}
-func ImportApiGroupFromAms(projectID, userID int, groupInfo entity.AmsGroupInfo) (bool, string, error) {
+//ImportAPIGroupFromAms 导入接口分组
+func ImportAPIGroupFromAms(projectID, userID int, groupInfo entity.AmsGroupInfo) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -102,55 +98,55 @@ func ImportApiGroupFromAms(projectID, userID int, groupInfo entity.AmsGroupInfo)
}
// 插入子分组信息
for _, value := range groupInfo.ChildGroupList {
- flag, secGroupID, secgroupPath := importApiGroupInfo(Tx, value.GroupName, groupPath, int(groupID), projectID, 2)
+ flag, secGroupID, secgroupPath := importAPIGroupInfo(Tx, value.GroupName, groupPath, int(groupID), projectID, 2)
if !flag {
continue
}
for _, v := range value.ChildGroupList {
- flag, thirdGroupID, thirdgroupPath := importApiGroupInfo(Tx, v.GroupName, secgroupPath, secGroupID, projectID, 3)
+ flag, thirdGroupID, thirdgroupPath := importAPIGroupInfo(Tx, v.GroupName, secgroupPath, secGroupID, projectID, 3)
if !flag {
continue
}
for _, vv := range v.ChildGroupList {
- flag, fourthGroupID, fourthgroupPath := importApiGroupInfo(Tx, vv.GroupName, thirdgroupPath, thirdGroupID, projectID, 4)
+ flag, fourthGroupID, fourthgroupPath := importAPIGroupInfo(Tx, vv.GroupName, thirdgroupPath, thirdGroupID, projectID, 4)
if !flag {
continue
}
for _, vvv := range vv.ChildGroupList {
- flag, fifthGroupID, _ := importApiGroupInfo(Tx, vvv.GroupName, fourthgroupPath, fourthGroupID, projectID, 5)
+ flag, fifthGroupID, _ := importAPIGroupInfo(Tx, vvv.GroupName, fourthgroupPath, fourthGroupID, projectID, 5)
if !flag {
continue
}
- for _, aaa := range vvv.ApiList {
- flag = importApiInfo(Tx, aaa, projectID, fifthGroupID, userID)
+ for _, aaa := range vvv.APIList {
+ flag = importAPIInfo(Tx, aaa, projectID, fifthGroupID, userID)
if !flag {
continue
}
}
}
- for _, aa := range vv.ApiList {
- flag = importApiInfo(Tx, aa, projectID, fourthGroupID, userID)
+ for _, aa := range vv.APIList {
+ flag = importAPIInfo(Tx, aa, projectID, fourthGroupID, userID)
if !flag {
continue
}
}
}
- for _, a := range v.ApiList {
- flag = importApiInfo(Tx, a, projectID, thirdGroupID, userID)
+ for _, a := range v.APIList {
+ flag = importAPIInfo(Tx, a, projectID, thirdGroupID, userID)
if !flag {
continue
}
}
}
- for _, api := range value.ApiList {
- flag := importApiInfo(Tx, api, projectID, secGroupID, userID)
+ for _, api := range value.APIList {
+ flag := importAPIInfo(Tx, api, projectID, secGroupID, userID)
if !flag {
continue
}
}
}
- for _, apiInfo := range groupInfo.ApiList {
- flag := importApiInfo(Tx, apiInfo, projectID, int(groupID), userID)
+ for _, apiInfo := range groupInfo.APIList {
+ flag := importAPIInfo(Tx, apiInfo, projectID, int(groupID), userID)
if !flag {
continue
}
@@ -165,7 +161,7 @@ func ImportApiGroupFromAms(projectID, userID int, groupInfo entity.AmsGroupInfo)
return true, "", nil
}
-// 导入项目
+// ImportProjectFromAms 导入项目
func ImportProjectFromAms(userID int, projectInfo entity.AmsProject) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
@@ -182,7 +178,7 @@ func ImportProjectFromAms(userID int, projectInfo entity.AmsProject) (bool, stri
log.Info(err.Error())
}
id := int(projectID)
- for _, groupInfo := range projectInfo.ApiGroupList {
+ for _, groupInfo := range projectInfo.APIGroupList {
// 插入分组信息
result, err := Tx.Exec("INSERT INTO goku_gateway_api_group (projectID,groupName,groupDepth) VALUES (?,?,1);", projectID, groupInfo.GroupName)
if err != nil {
@@ -204,56 +200,56 @@ func ImportProjectFromAms(userID int, projectInfo entity.AmsProject) (bool, stri
}
// 插入子分组信息
- for _, value := range groupInfo.ApiGroupChildList {
- flag, secGroupID, secgroupPath := importApiGroupInfo(Tx, value.GroupName, groupPath, int(groupID), id, 2)
+ for _, value := range groupInfo.APIGroupChildList {
+ flag, secGroupID, secgroupPath := importAPIGroupInfo(Tx, value.GroupName, groupPath, int(groupID), id, 2)
if !flag {
continue
}
- for _, v := range value.ApiGroupChildList {
- flag, thirdGroupID, thirdgroupPath := importApiGroupInfo(Tx, v.GroupName, secgroupPath, secGroupID, id, 3)
+ for _, v := range value.APIGroupChildList {
+ flag, thirdGroupID, thirdgroupPath := importAPIGroupInfo(Tx, v.GroupName, secgroupPath, secGroupID, id, 3)
if !flag {
continue
}
- for _, vv := range v.ApiGroupChildList {
- flag, fourthGroupID, fourthgroupPath := importApiGroupInfo(Tx, vv.GroupName, thirdgroupPath, thirdGroupID, id, 4)
+ for _, vv := range v.APIGroupChildList {
+ flag, fourthGroupID, fourthgroupPath := importAPIGroupInfo(Tx, vv.GroupName, thirdgroupPath, thirdGroupID, id, 4)
if !flag {
continue
}
- for _, vvv := range vv.ApiGroupChildList {
- flag, fifthGroupID, _ := importApiGroupInfo(Tx, vvv.GroupName, fourthgroupPath, fourthGroupID, id, 5)
+ for _, vvv := range vv.APIGroupChildList {
+ flag, fifthGroupID, _ := importAPIGroupInfo(Tx, vvv.GroupName, fourthgroupPath, fourthGroupID, id, 5)
if !flag {
continue
}
- for _, aaa := range v.ApiList {
- flag = importApiInfo(Tx, aaa, id, fifthGroupID, userID)
+ for _, aaa := range v.APIList {
+ flag = importAPIInfo(Tx, aaa, id, fifthGroupID, userID)
if !flag {
continue
}
}
}
- for _, aa := range v.ApiList {
- flag = importApiInfo(Tx, aa, id, fourthGroupID, userID)
+ for _, aa := range v.APIList {
+ flag = importAPIInfo(Tx, aa, id, fourthGroupID, userID)
if !flag {
continue
}
}
}
- for _, a := range v.ApiList {
- flag = importApiInfo(Tx, a, id, thirdGroupID, userID)
+ for _, a := range v.APIList {
+ flag = importAPIInfo(Tx, a, id, thirdGroupID, userID)
if !flag {
continue
}
}
}
- for _, api := range value.ApiList {
- flag = importApiInfo(Tx, api, id, secGroupID, userID)
+ for _, api := range value.APIList {
+ flag = importAPIInfo(Tx, api, id, secGroupID, userID)
if !flag {
continue
}
}
}
- for _, apiInfo := range groupInfo.ApiList {
- flag := importApiInfo(Tx, apiInfo, id, int(groupID), userID)
+ for _, apiInfo := range groupInfo.APIList {
+ flag := importAPIInfo(Tx, apiInfo, id, int(groupID), userID)
if !flag {
continue
}
@@ -263,7 +259,8 @@ func ImportProjectFromAms(userID int, projectInfo entity.AmsProject) (bool, stri
return true, "", nil
}
-func ImportApiFromAms(projectID, groupID, userID int, apiList []entity.AmsApiInfo) (bool, string, error) {
+//ImportAPIFromAms 导入接口
+func ImportAPIFromAms(projectID, groupID, userID int, apiList []entity.AmsAPIInfo) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -271,18 +268,18 @@ func ImportApiFromAms(projectID, groupID, userID int, apiList []entity.AmsApiInf
// 新增API
requestURL := ""
host := ""
- u, err := url.ParseRequestURI(apiInfo.BaseInfo.ApiURI)
+ u, err := url.ParseRequestURI(apiInfo.BaseInfo.APIURI)
if err == nil {
requestURL = u.Path
if u.Scheme != "" && u.Host != "" {
host = u.Scheme + "://" + u.Host
}
} else {
- requestURL = apiInfo.BaseInfo.ApiURI
+ requestURL = apiInfo.BaseInfo.APIURI
}
now = time.Now().Format("2006-01-02 15:04:05")
- requestMethod := method[apiInfo.BaseInfo.ApiRequestType]
- _, err = Tx.Exec("INSERT INTO goku_gateway_api (projectID,groupID,apiName,requestURL,targetURL,requestMethod,targetServer,targetMethod,isFollow,stripPrefix,timeout,retryCount,createTime,updateTime,managerID,lastUpdateUserID,createUserID) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);", projectID, groupID, apiInfo.BaseInfo.ApiName, requestURL, requestURL, requestMethod, host, requestMethod, "true", "true", 2000, 0, now, now, userID, userID, userID)
+ requestMethod := method[apiInfo.BaseInfo.APIRequestType]
+ _, err = Tx.Exec("INSERT INTO goku_gateway_api (projectID,groupID,apiName,requestURL,targetURL,requestMethod,targetServer,targetMethod,isFollow,stripPrefix,timeout,retryCount,createTime,updateTime,managerID,lastUpdateUserID,createUserID) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);", projectID, groupID, apiInfo.BaseInfo.APIName, requestURL, requestURL, requestMethod, host, requestMethod, "true", "true", 2000, 0, now, now, userID, userID, userID)
if err != nil {
Tx.Rollback()
log.Info(err.Error())
diff --git a/server/dao/console-mysql/node.go b/server/dao/console-mysql/node.go
index 23175b7..c0434bc 100644
--- a/server/dao/console-mysql/node.go
+++ b/server/dao/console-mysql/node.go
@@ -1,17 +1,17 @@
-package console_mysql
+package consolemysql
import (
"fmt"
"github.com/eolinker/goku-api-gateway/common/database"
- . "github.com/eolinker/goku-api-gateway/common/version"
+ v "github.com/eolinker/goku-api-gateway/common/version"
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
"strconv"
"strings"
"time"
)
-// 新增节点信息
-func AddNode(clusterId int, nodeName, nodeIP, nodePort, gatewayPath string, groupID int) (bool, map[string]interface{}, error) {
+// AddNode 新增节点信息
+func AddNode(clusterID int, nodeName, nodeIP, nodePort, gatewayPath string, groupID int) (bool, map[string]interface{}, error) {
db := database.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
sql := "INSERT INTO goku_node_info (`clusterID`,`nodeName`,`groupID`,`nodeIP`,`nodePort`,`updateTime`,`createTime`,`version`, `gatewayPath`,`nodeStatus`) VALUES (?,?,?,?,?,?,?,?,?,0);"
@@ -20,19 +20,18 @@ func AddNode(clusterId int, nodeName, nodeIP, nodePort, gatewayPath string, grou
return false, map[string]interface{}{"error": "[ERROR]Illegal SQL statement!"}, err
}
defer stmt.Close()
- res, err := stmt.Exec(clusterId, nodeName, groupID, nodeIP, nodePort, now, now, Version, gatewayPath)
+ res, err := stmt.Exec(clusterID, nodeName, groupID, nodeIP, nodePort, now, now, v.Version, gatewayPath)
if err != nil {
return false, map[string]interface{}{"error": "[ERROR]Failed to insert data!"}, err
- } else {
- nodeID, err := res.LastInsertId()
- if err != nil {
- return false, map[string]interface{}{"error": "[ERROR]Failed to insert data!"}, err
- }
- return true, map[string]interface{}{"nodeID": nodeID, "version": Version}, nil
}
+ nodeID, err := res.LastInsertId()
+ if err != nil {
+ return false, map[string]interface{}{"error": "[ERROR]Failed to insert data!"}, err
+ }
+ return true, map[string]interface{}{"nodeID": nodeID, "version": v.Version}, nil
}
-// 修改节点信息
+// EditNode 修改节点信息
func EditNode(nodeName, nodeIP, nodePort, gatewayPath string, nodeID, groupID int) (bool, string, error) {
db := database.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -45,12 +44,11 @@ func EditNode(nodeName, nodeIP, nodePort, gatewayPath string, nodeID, groupID in
_, err = stmt.Exec(nodeName, nodeIP, nodePort, now, groupID, gatewayPath, nodeID)
if err != nil {
return false, "[ERROR]Failed to update data!", err
- } else {
- return true, "", nil
}
+ return true, "", nil
}
-// 删除节点信息
+// DeleteNode 删除节点信息
func DeleteNode(nodeID int) (bool, string, error) {
db := database.GetConnection()
sql := "DELETE FROM goku_node_info WHERE nodeID = ?;"
@@ -62,9 +60,8 @@ func DeleteNode(nodeID int) (bool, string, error) {
_, err = stmt.Exec(nodeID)
if err != nil {
return false, "[ERROR]Failed to delete data!", err
- } else {
- return true, "", nil
}
+ return true, "", nil
}
// GetNodeList 获取节点列表
@@ -101,7 +98,7 @@ func GetNodeList(clusterID, groupID int, keyword string) (bool, []*entity.Node,
panic(err)
return false, nil, err
}
- if node.Version == Version {
+ if node.Version == v.Version {
// 判断节点版本号是否是最新
node.IsUpdate = true
}
@@ -110,8 +107,8 @@ func GetNodeList(clusterID, groupID int, keyword string) (bool, []*entity.Node,
return true, nodeList, nil
}
-const nodeSqlIpPort = "SELECT A.`nodeID`, A.`nodeName`, A.`nodeIP`, A.`nodePort`, A.`updateTime`, A.`createTime`, A.`version`, A.`gatewayPath`, A.`groupID`, IFNULL(G.`groupName`,'') , C.`name` As cluster, C.`title` As cluster_title FROM goku_node_info A LEFT JOIN goku_node_group G ON A.`groupID` = G.`groupID` LEFT JOIN `goku_cluster` C ON A.`clusterID` = C.`id`WHERE A.`nodeIP` = ? and A.`nodePort`=?;"
-const nodeSqlId = "SELECT A.`nodeID`, A.`nodeName`, A.`nodeIP`, A.`nodePort`, A.`updateTime`, A.`createTime`, A.`version`, A.`gatewayPath`, A.`groupID`, IFNULL(G.`groupName`,''), C.`name` As cluster, C.`title` As cluster_title FROM goku_node_info A LEFT JOIN goku_node_group G ON A.`groupID` = G.`groupID` LEFT JOIN `goku_cluster` C ON A.`clusterID` = C.`id`WHERE A.`nodeID` = ? ;"
+const nodeSQLIPPort = "SELECT A.`nodeID`, A.`nodeName`, A.`nodeIP`, A.`nodePort`, A.`updateTime`, A.`createTime`, A.`version`, A.`gatewayPath`, A.`groupID`, IFNULL(G.`groupName`,'') , C.`name` As cluster, C.`title` As cluster_title FROM goku_node_info A LEFT JOIN goku_node_group G ON A.`groupID` = G.`groupID` LEFT JOIN `goku_cluster` C ON A.`clusterID` = C.`id`WHERE A.`nodeIP` = ? and A.`nodePort`=?;"
+const nodeSQLID = "SELECT A.`nodeID`, A.`nodeName`, A.`nodeIP`, A.`nodePort`, A.`updateTime`, A.`createTime`, A.`version`, A.`gatewayPath`, A.`groupID`, IFNULL(G.`groupName`,''), C.`name` As cluster, C.`title` As cluster_title FROM goku_node_info A LEFT JOIN goku_node_group G ON A.`groupID` = G.`groupID` LEFT JOIN `goku_cluster` C ON A.`clusterID` = C.`id`WHERE A.`nodeID` = ? ;"
func getNodeInfo(sql string, args ...interface{}) (bool, *entity.Node, error) {
@@ -136,17 +133,19 @@ func getNodeInfo(sql string, args ...interface{}) (bool, *entity.Node, error) {
return true, node, err
}
-// 获取节点信息
+// GetNodeInfo 获取节点信息
func GetNodeInfo(nodeID int) (bool, *entity.Node, error) {
- return getNodeInfo(nodeSqlId, nodeID)
+ return getNodeInfo(nodeSQLID, nodeID)
}
-func GetNodeByIpPort(ip string, port int) (bool, *entity.Node, error) {
- return getNodeInfo(nodeSqlIpPort, ip, port)
+//GetNodeByIPPort 通过IP+端口获取节点信息
+func GetNodeByIPPort(ip string, port int) (bool, *entity.Node, error) {
+
+ return getNodeInfo(nodeSQLIPPort, ip, port)
}
-// 节点IP查重
+// CheckIsExistRemoteAddr 节点IP查重
func CheckIsExistRemoteAddr(nodeID int, nodeIP, nodePort string) bool {
db := database.GetConnection()
sql := `SELECT nodeID FROM goku_node_info WHERE nodeIP = ? AND nodePort = ?;`
@@ -157,12 +156,11 @@ func CheckIsExistRemoteAddr(nodeID int, nodeIP, nodePort string) bool {
}
if id == nodeID {
return false
- } else {
- return true
}
+ return true
}
-// 获取节点IP列表
+// GetNodeIPList 获取节点IP列表
func GetNodeIPList() (bool, []map[string]interface{}, error) {
db := database.GetConnection()
sql := `SELECT nodeID,nodeIP,nodePort FROM goku_node_info WHERE nodeStatus = 1;`
@@ -174,27 +172,24 @@ func GetNodeIPList() (bool, []map[string]interface{}, error) {
defer rows.Close()
//获取记录列
nodeList := make([]map[string]interface{}, 0)
- if _, err = rows.Columns(); err != nil {
- return false, make([]map[string]interface{}, 0), err
- } else {
- for rows.Next() {
- var nodeID int
- var nodeIP, nodePort string
- err = rows.Scan(&nodeID, &nodeIP, &nodePort)
- if err != nil {
- return false, make([]map[string]interface{}, 0), err
- }
- nodeList = append(nodeList, map[string]interface{}{
- "nodeID": nodeID,
- "nodeIP": nodeIP,
- "nodePort": nodePort,
- })
+
+ for rows.Next() {
+ var nodeID int
+ var nodeIP, nodePort string
+ err = rows.Scan(&nodeID, &nodeIP, &nodePort)
+ if err != nil {
+ return false, make([]map[string]interface{}, 0), err
}
- return true, nodeList, nil
+ nodeList = append(nodeList, map[string]interface{}{
+ "nodeID": nodeID,
+ "nodeIP": nodeIP,
+ "nodePort": nodePort,
+ })
}
+ return true, nodeList, nil
}
-// 从待操作节点中获取关闭节点列表
+// GetAvaliableNodeListFromNodeList 从待操作节点中获取关闭节点列表
func GetAvaliableNodeListFromNodeList(nodeIDList string, nodeStatus int) (bool, string, error) {
db := database.GetConnection()
sql := "SELECT nodeID FROM goku_node_info WHERE nodeID IN (" + nodeIDList + ") AND nodeStatus = ?"
@@ -216,7 +211,7 @@ func GetAvaliableNodeListFromNodeList(nodeIDList string, nodeStatus int) (bool,
return true, strings.Join(idList, ","), nil
}
-// 批量修改节点分组
+// BatchEditNodeGroup 批量修改节点分组
func BatchEditNodeGroup(nodeIDList string, groupID int) (bool, string, error) {
db := database.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -231,7 +226,7 @@ func BatchEditNodeGroup(nodeIDList string, groupID int) (bool, string, error) {
return true, "", nil
}
-// 批量修改接口分组
+// BatchDeleteNode 批量修改接口分组
func BatchDeleteNode(nodeIDList string) (bool, string, error) {
db := database.GetConnection()
Tx, _ := db.Begin()
@@ -245,7 +240,7 @@ func BatchDeleteNode(nodeIDList string) (bool, string, error) {
return true, "", nil
}
-// 更新节点集群ID
+// UpdateAllNodeClusterID 更新节点集群ID
func UpdateAllNodeClusterID(clusterID int) {
db := database.GetConnection()
Tx, _ := db.Begin()
diff --git a/server/dao/console-mysql/nodeGroup.go b/server/dao/console-mysql/nodeGroup.go
index e912969..527b3a7 100644
--- a/server/dao/console-mysql/nodeGroup.go
+++ b/server/dao/console-mysql/nodeGroup.go
@@ -1,11 +1,11 @@
-package console_mysql
+package consolemysql
import (
database2 "github.com/eolinker/goku-api-gateway/common/database"
)
-// 新建节点分组
-func AddNodeGroup(groupName string, clusterId int) (bool, interface{}, error) {
+// AddNodeGroup 新建节点分组
+func AddNodeGroup(groupName string, clusterID int) (bool, interface{}, error) {
db := database2.GetConnection()
sql := "INSERT INTO goku_node_group (`groupName`,`clusterID`) VALUES (?,?);"
stmt, err := db.Prepare(sql)
@@ -13,7 +13,7 @@ func AddNodeGroup(groupName string, clusterId int) (bool, interface{}, error) {
return false, err.Error(), err
}
defer stmt.Close()
- r, err := stmt.Exec(groupName, clusterId)
+ r, err := stmt.Exec(groupName, clusterID)
if err != nil {
return false, "[ERROR]Fail to insert data!", err
}
@@ -21,7 +21,7 @@ func AddNodeGroup(groupName string, clusterId int) (bool, interface{}, error) {
return true, groupID, nil
}
-// 修改节点分组信息
+// EditNodeGroup 修改节点分组信息
func EditNodeGroup(groupName string, groupID int) (bool, string, error) {
db := database2.GetConnection()
sql := "UPDATE goku_node_group SET groupName = ? WHERE groupID = ?;"
@@ -37,7 +37,7 @@ func EditNodeGroup(groupName string, groupID int) (bool, string, error) {
return true, "", nil
}
-// 删除节点分组
+// DeleteNodeGroup 删除节点分组
func DeleteNodeGroup(groupID int) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
@@ -57,7 +57,7 @@ func DeleteNodeGroup(groupID int) (bool, string, error) {
return true, "", nil
}
-// 获取节点分组信息
+// GetNodeGroupInfo 获取节点分组信息
func GetNodeGroupInfo(groupID int) (bool, map[string]interface{}, error) {
db := database2.GetConnection()
@@ -76,42 +76,37 @@ func GetNodeGroupInfo(groupID int) (bool, map[string]interface{}, error) {
return true, groupInfo, nil
}
-// 获取节点分组列表
-func GetNodeGroupList(clusterId int) (bool, []map[string]interface{}, error) {
+// GetNodeGroupList 获取节点分组列表
+func GetNodeGroupList(clusterID int) (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
sql := "SELECT G.`groupID`, G.groupName,C.`name` as cluster FROM goku_node_group G left join `goku_cluster` C ON C.`id` = G.`clusterID` where G.`clusterID`=?;"
- rows, err := db.Query(sql, clusterId)
+ rows, err := db.Query(sql, clusterID)
if err != nil {
return false, nil, err
}
//延时关闭Rows
defer rows.Close()
//获取记录列
-
- if _, err = rows.Columns(); err != nil {
- return false, nil, err
- } else {
- nodeGroupList := make([]map[string]interface{}, 0)
- for rows.Next() {
- var groupID int
- var groupName string
- var clusterName string
- err = rows.Scan(&groupID, &groupName, &clusterName)
- if err != nil {
- return false, nil, err
- }
- groupInfo := map[string]interface{}{
- "groupID": groupID,
- "groupName": groupName,
- "cluster": clusterName,
- }
- nodeGroupList = append(nodeGroupList, groupInfo)
+ nodeGroupList := make([]map[string]interface{}, 0)
+ for rows.Next() {
+ var groupID int
+ var groupName string
+ var clusterName string
+ err = rows.Scan(&groupID, &groupName, &clusterName)
+ if err != nil {
+ return false, nil, err
+ }
+ groupInfo := map[string]interface{}{
+ "groupID": groupID,
+ "groupName": groupName,
+ "cluster": clusterName,
}
- return true, nodeGroupList, nil
+ nodeGroupList = append(nodeGroupList, groupInfo)
}
+ return true, nodeGroupList, nil
}
-// 检查节点分组是否存在
+// CheckNodeGroupIsExist 检查节点分组是否存在
func CheckNodeGroupIsExist(groupID int) (bool, error) {
db := database2.GetConnection()
var id int
@@ -123,7 +118,7 @@ func CheckNodeGroupIsExist(groupID int) (bool, error) {
return true, nil
}
-// 获取分组内启动节点数量
+// GetRunningNodeCount 获取分组内启动节点数量
func GetRunningNodeCount(groupID int) (bool, interface{}, error) {
db := database2.GetConnection()
var count int
diff --git a/server/dao/console-mysql/plugin.go b/server/dao/console-mysql/plugin.go
index 44bd28a..fa0131d 100644
--- a/server/dao/console-mysql/plugin.go
+++ b/server/dao/console-mysql/plugin.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
SQL "database/sql"
@@ -13,7 +13,7 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// 获取插件配置信息
+//GetPluginInfo 获取插件配置信息
func GetPluginInfo(pluginName string) (bool, *entity.Plugin, error) {
db := database2.GetConnection()
sql := `SELECT pluginID,pluginName,pluginStatus,IFNULL(pluginConfig,""),pluginPriority,isStop,IFNULL(pluginDesc,""),IFNULL(version,""),pluginType FROM goku_plugin WHERE pluginName = ?;`
@@ -51,20 +51,17 @@ func GetPluginList(keyword string, condition int) (bool, []*entity.Plugin, error
defer rows.Close()
//获取记录列
pluginList := make([]*entity.Plugin, 0)
- if _, err = rows.Columns(); err != nil {
- return false, make([]*entity.Plugin, 0), err
- } else {
- for rows.Next() {
- var plugin entity.Plugin
- err = rows.Scan(&plugin.PluginID, &plugin.ChineseName, &plugin.PluginName, &plugin.PluginStatus, &plugin.PluginIndex, &plugin.PluginDesc, &plugin.IsStop, &plugin.PluginType, &plugin.Version, &plugin.IsCheck)
- if err != nil {
- return false, make([]*entity.Plugin, 0), err
- }
- pluginList = append(pluginList, &plugin)
+
+ for rows.Next() {
+ var plugin entity.Plugin
+ err = rows.Scan(&plugin.PluginID, &plugin.ChineseName, &plugin.PluginName, &plugin.PluginStatus, &plugin.PluginIndex, &plugin.PluginDesc, &plugin.IsStop, &plugin.PluginType, &plugin.Version, &plugin.IsCheck)
+ if err != nil {
+ return false, make([]*entity.Plugin, 0), err
}
- // sort.Sort(sort.Reverse(entity.PluginSlice(pluginList)))
- return true, pluginList, nil
+ pluginList = append(pluginList, &plugin)
}
+ // sort.Sort(sort.Reverse(entity.PluginSlice(pluginList)))
+ return true, pluginList, nil
}
// AddPlugin 新增插件信息
@@ -79,9 +76,8 @@ func AddPlugin(pluginName, pluginConfig, pluginDesc, version string, pluginPrior
if err != nil {
panic(err)
return false, "[ERROR]Failed to insert data!", err
- } else {
- return true, "", nil
}
+ return true, "", nil
}
// EditPlugin 修改插件信息
@@ -132,7 +128,7 @@ func DeletePlugin(pluginName string) (bool, string, error) {
return false, "[ERROR]The plugin is not exist!", err
}
if official == "true" {
- return false, "[ERROR]Can not delete goku plugin!", errors.New("[ERROR]Can not delete goku plugin!")
+ return false, "[error]can not delete goku plugin!", errors.New("[error]can not delete goku plugin")
}
Tx, _ := db.Begin()
_, err = Tx.Exec(`DELETE FROM goku_plugin WHERE pluginName = ?`, pluginName)
@@ -150,7 +146,7 @@ func DeletePlugin(pluginName string) (bool, string, error) {
return true, "", nil
}
-// 判断插件ID是否存在
+//CheckIndexIsExist 判断插件ID是否存在
func CheckIndexIsExist(pluginName string, pluginPriority int) (bool, error) {
db := database2.GetConnection()
sql := "SELECT pluginName FROM goku_plugin WHERE pluginPriority = ?;"
@@ -158,15 +154,14 @@ func CheckIndexIsExist(pluginName string, pluginPriority int) (bool, error) {
err := db.QueryRow(sql, pluginPriority).Scan(&p)
if err != nil {
return false, err
- } else {
- if pluginName == p {
- return false, err
- }
- return true, nil
}
+ if pluginName == p {
+ return false, err
+ }
+ return true, nil
}
-// 获取插件配置及插件信息
+//GetPluginConfig 获取插件配置及插件信息
func GetPluginConfig(pluginName string) (bool, string, error) {
db := database2.GetConnection()
sql := `SELECT IFNULL(pluginConfig,"") FROM goku_plugin WHERE pluginName = ?`
@@ -178,7 +173,7 @@ func GetPluginConfig(pluginName string) (bool, string, error) {
return true, pluginConfig, nil
}
-// 检查插件名称是否存在
+//CheckNameIsExist 检查插件名称是否存在
func CheckNameIsExist(pluginName string) (bool, error) {
db := database2.GetConnection()
sql := "SELECT pluginName FROM goku_plugin WHERE pluginName = ?;"
@@ -186,12 +181,11 @@ func CheckNameIsExist(pluginName string) (bool, error) {
err := db.QueryRow(sql, pluginName).Scan(&p)
if err != nil {
return false, err
- } else {
- return true, err
}
+ return true, err
}
-// 修改插件开启状态
+//EditPluginStatus 修改插件开启状态
func EditPluginStatus(pluginName string, pluginStatus int) (bool, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
@@ -208,14 +202,13 @@ func EditPluginStatus(pluginName string, pluginStatus int) (bool, error) {
if err != nil {
Tx.Rollback()
return false, err
- } else {
- // 获取使用该插件的策略组列表
- Tx.Commit()
- return true, nil
}
+ // 获取使用该插件的策略组列表
+ Tx.Commit()
+ return true, nil
}
-// 获取不同类型的插件列表
+//GetPluginListByPluginType 获取不同类型的插件列表
func GetPluginListByPluginType(pluginType int) (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
sql := `SELECT pluginID,pluginName,pluginDesc FROM goku_plugin WHERE pluginType = ? AND pluginStatus = 1;`
@@ -228,29 +221,25 @@ func GetPluginListByPluginType(pluginType int) (bool, []map[string]interface{},
defer rows.Close()
//获取记录列
pluginList := make([]map[string]interface{}, 0)
- if _, err = rows.Columns(); err != nil {
- return false, make([]map[string]interface{}, 0), err
- } else {
- for rows.Next() {
- var pluginID int
- var pluginName, chineseName string
- err = rows.Scan(&pluginID, &pluginName, &chineseName)
- if err != nil {
- return false, make([]map[string]interface{}, 0), err
- }
- plugin := map[string]interface{}{
- "pluginID": pluginID,
- "pluginName": pluginName,
- "pluginType": pluginType,
- "chineseName": chineseName,
- }
- pluginList = append(pluginList, plugin)
+ for rows.Next() {
+ var pluginID int
+ var pluginName, chineseName string
+ err = rows.Scan(&pluginID, &pluginName, &chineseName)
+ if err != nil {
+ return false, make([]map[string]interface{}, 0), err
}
- return true, pluginList, nil
+ plugin := map[string]interface{}{
+ "pluginID": pluginID,
+ "pluginName": pluginName,
+ "pluginType": pluginType,
+ "chineseName": chineseName,
+ }
+ pluginList = append(pluginList, plugin)
}
+ return true, pluginList, nil
}
-// 批量关闭插件
+//BatchStopPlugin 批量关闭插件
func BatchStopPlugin(pluginNameList string) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
@@ -274,7 +263,7 @@ func BatchStopPlugin(pluginNameList string) (bool, string, error) {
return true, "", nil
}
-// 批量关闭插件
+//BatchStartPlugin 批量关闭插件
func BatchStartPlugin(pluginNameList string) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
@@ -298,7 +287,7 @@ func BatchStartPlugin(pluginNameList string) (bool, string, error) {
return true, "", nil
}
-// 将插件配置写进缓存表中
+//EditPluginCache 将插件配置写进缓存表中
func EditPluginCache(pluginName string, oldPluginType, pluginType int, Tx *SQL.Tx) (bool, error) {
if oldPluginType == 1 {
@@ -312,28 +301,25 @@ func EditPluginCache(pluginName string, oldPluginType, pluginType int, Tx *SQL.T
//延时关闭Rows
defer rows.Close()
//获取记录列
- if _, err = rows.Columns(); err != nil {
- return false, err
- } else {
- for rows.Next() {
- var strategyID string
- err = rows.Scan(&strategyID)
+
+ for rows.Next() {
+ var strategyID string
+ err = rows.Scan(&strategyID)
+ if err != nil {
+ return false, err
+ }
+ strategyIDList = append(strategyIDList, strategyID)
+ }
+ if len(strategyIDList) > 0 {
+ if oldPluginType != pluginType {
+ // 删除策略组插件
+ _, err = Tx.Exec("DELETE FROM goku_conn_plugin_strategy WHERE strategyID AND pluginName = ?;", pluginName)
if err != nil {
return false, err
}
- strategyIDList = append(strategyIDList, strategyID)
- }
- if len(strategyIDList) > 0 {
- if oldPluginType != pluginType {
- // 删除策略组插件
- _, err = Tx.Exec("DELETE FROM goku_conn_plugin_strategy WHERE strategyID AND pluginName = ?;", pluginName)
- if err != nil {
- return false, err
- }
- }
}
- return true, nil
}
+ return true, nil
} else if oldPluginType == 2 {
// 获取策略ID列表
sql := "SELECT strategyID,apiID FROM goku_conn_plugin_api WHERE pluginName = ?;"
@@ -345,48 +331,45 @@ func EditPluginCache(pluginName string, oldPluginType, pluginType int, Tx *SQL.T
//延时关闭Rows
defer rows.Close()
//获取记录列
- if _, err = rows.Columns(); err != nil {
- return false, err
- } else {
- for rows.Next() {
- var strategyID string
- var apiID int
- err = rows.Scan(&strategyID, &apiID)
+
+ for rows.Next() {
+ var strategyID string
+ var apiID int
+ err = rows.Scan(&strategyID, &apiID)
+ if err != nil {
+ return false, err
+ }
+ connList = append(connList, map[string]interface{}{
+ "strategyID": strategyID,
+ "apiID": apiID,
+ })
+ }
+ if len(connList) > 0 {
+ if oldPluginType != pluginType {
+ // 删除接口插件
+ _, err = Tx.Exec("DELETE FROM goku_conn_plugin_api WHERE pluginName = ?;", pluginName)
if err != nil {
return false, err
}
- connList = append(connList, map[string]interface{}{
- "strategyID": strategyID,
- "apiID": apiID,
- })
- }
- if len(connList) > 0 {
- if oldPluginType != pluginType {
- // 删除接口插件
- _, err = Tx.Exec("DELETE FROM goku_conn_plugin_api WHERE pluginName = ?;", pluginName)
- if err != nil {
- return false, err
- }
- }
}
- return true, nil
}
+ return true, nil
}
return true, nil
}
-// 更新插件检测状态
+//EditPluginCheckStatus 更新插件检测状态
func EditPluginCheckStatus(pluginName string, isCheck int) (bool, string, error) {
db := database2.GetConnection()
sql := "UPDATE goku_plugin SET isCheck = ? WHERE pluginName = ?;"
_, err := db.Exec(sql, isCheck, pluginName)
if err != nil {
return false, "[ERROR]Fail to update data", err
- } else {
- return true, "", nil
}
+ return true, "", nil
}
+//UpdatePluginTagByPluginName 更新插件标志位
func UpdatePluginTagByPluginName(pluginList string) error {
db := database2.GetConnection()
plugins := strings.Split(pluginList, ",")
diff --git a/server/dao/console-mysql/project.go b/server/dao/console-mysql/project.go
index a492909..1959966 100644
--- a/server/dao/console-mysql/project.go
+++ b/server/dao/console-mysql/project.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
"fmt"
@@ -11,7 +11,7 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
)
-// 新建项目
+//AddProject 新建项目
func AddProject(projectName string) (bool, interface{}, error) {
now := time.Now().Format("2006-01-02 15:04:05")
db := database2.GetConnection()
@@ -29,7 +29,7 @@ func AddProject(projectName string) (bool, interface{}, error) {
return true, projectID, nil
}
-// 修改项目信息
+//EditProject 修改项目信息
func EditProject(projectName string, projectID int) (bool, string, error) {
now := time.Now().Format("2006-01-02 15:04:05")
db := database2.GetConnection()
@@ -46,7 +46,7 @@ func EditProject(projectName string, projectID int) (bool, string, error) {
return true, "", nil
}
-// 修改项目信息
+//DeleteProject 修改项目信息
func DeleteProject(projectID int) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
@@ -152,7 +152,7 @@ func DeleteProject(projectID int) (bool, string, error) {
return true, "", nil
}
-// 批量删除项目
+//BatchDeleteProject 批量删除项目
func BatchDeleteProject(projectIDList string) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
@@ -226,13 +226,6 @@ func BatchDeleteProject(projectIDList string) (bool, string, error) {
return false, "[ERROR]Fail to excute SQL statement!", err
}
- //sql = "DELETE FROM goku_gateway_api_cache WHERE apiID IN (" + apiIDList + ");"
- //_, err = Tx.Exec(sql)
- //if err != nil {
- // Tx.Rollback()
- // return false, "[ERROR]Fail to excute SQL statement!", err
- //}
-
sql = "DELETE FROM goku_conn_plugin_api WHERE apiID IN (" + apiIDList + ");"
_, err = Tx.Exec(sql)
if err != nil {
@@ -252,7 +245,7 @@ func BatchDeleteProject(projectIDList string) (bool, string, error) {
return true, "", nil
}
-// 获取项目信息
+//GetProjectInfo 获取项目信息
func GetProjectInfo(projectID int) (bool, entity.Project, error) {
db := database2.GetConnection()
var project entity.Project
@@ -264,7 +257,7 @@ func GetProjectInfo(projectID int) (bool, entity.Project, error) {
return true, project, nil
}
-// 获取项目列表
+//GetProjectList 获取项目列表
func GetProjectList(keyword string) (bool, []*entity.Project, error) {
sql := "SELECT `projectID`,`projectName`,`updateTime` FROM `goku_gateway_project` %s ORDER BY `updateTime` DESC;"
@@ -303,7 +296,7 @@ func GetProjectList(keyword string) (bool, []*entity.Project, error) {
}
-// 检查项目是否存在
+//CheckProjectIsExist 检查项目是否存在
func CheckProjectIsExist(projectID int) (bool, error) {
db := database2.GetConnection()
sql := "SELECT projectID FROM goku_gateway_project WHERE projectID = ?;"
@@ -311,13 +304,12 @@ func CheckProjectIsExist(projectID int) (bool, error) {
err := db.QueryRow(sql, projectID).Scan(&id)
if err != nil {
return false, err
- } else {
- return true, err
}
+ return true, err
}
-// 获取项目列表中没有被策略组绑定的接口
-func GetApiListFromProjectNotInStrategy() (bool, []map[string]interface{}, error) {
+//GetAPIListFromProjectNotInStrategy 获取项目列表中没有被策略组绑定的接口
+func GetAPIListFromProjectNotInStrategy() (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
sql := "SELECT projectID,projectName FROM goku_gateway_project;"
projectRows, err := db.Query(sql)
@@ -345,33 +337,28 @@ func GetApiListFromProjectNotInStrategy() (bool, []map[string]interface{}, error
}
defer rows.Close()
//获取记录列
- if _, err = rows.Columns(); err != nil {
- log.Info(err)
- return false, nil, err
- } else {
- groupList := make([]map[string]interface{}, 0, 20)
- for rows.Next() {
- var groupID, parentGroupID, groupDepth int
- var groupName string
- err = rows.Scan(&groupID, &groupName, &parentGroupID, &groupDepth)
- if err != nil {
- return false, nil, err
- }
- groupInfo := map[string]interface{}{
- "groupID": groupID,
- "groupName": groupName,
- "groupDepth": groupDepth,
- "parentGroupID": parentGroupID,
- }
- groupList = append(groupList, groupInfo)
+ groupList := make([]map[string]interface{}, 0, 20)
+ for rows.Next() {
+ var groupID, parentGroupID, groupDepth int
+ var groupName string
+ err = rows.Scan(&groupID, &groupName, &parentGroupID, &groupDepth)
+ if err != nil {
+ return false, nil, err
}
- projectInfo := map[string]interface{}{
- "projectID": projectID,
- "projectName": projectName,
- "groupList": groupList,
+ groupInfo := map[string]interface{}{
+ "groupID": groupID,
+ "groupName": groupName,
+ "groupDepth": groupDepth,
+ "parentGroupID": parentGroupID,
}
- projectList = append(projectList, projectInfo)
+ groupList = append(groupList, groupInfo)
+ }
+ projectInfo := map[string]interface{}{
+ "projectID": projectID,
+ "projectName": projectName,
+ "groupList": groupList,
}
+ projectList = append(projectList, projectInfo)
}
return true, projectList, nil
diff --git a/server/dao/console-mysql/redis.go b/server/dao/console-mysql/redis.go
index 7f96ec1..4969a27 100644
--- a/server/dao/console-mysql/redis.go
+++ b/server/dao/console-mysql/redis.go
@@ -1,128 +1,22 @@
-package console_mysql
+package consolemysql
import (
- "encoding/json"
database2 "github.com/eolinker/goku-api-gateway/common/database"
"github.com/eolinker/goku-api-gateway/common/general"
log "github.com/eolinker/goku-api-gateway/goku-log"
"github.com/eolinker/goku-api-gateway/server/entity/console-entity"
- "io"
"strings"
- "time"
)
func init() {
general.RegeditLater(CreateTable)
}
-func SaveMemoryInfo(server string, used int, peak int) int64 {
- db := database2.GetConnection()
-
- stmt, err := db.Prepare("INSERT INTO `goku_redis_memory`(used,peak,server,datetime) VALUES(?,?,?,?)")
- if err != nil {
- log.Info(err.Error())
- return 0
- }
- defer stmt.Close()
- datetime := time.Now().Format("2006-01-02 15:04:05")
- ret, err := stmt.Exec(used, peak, server, datetime)
- if err != nil {
- log.Info(err.Error())
- return 0
- }
- id, err := ret.LastInsertId()
- if err != nil {
- log.Info(err.Error())
- return 0
- }
- return id
-}
-
-func SaveInfoCommand(server string, info map[string]interface{}) int64 {
-
- datetime := time.Now().Format("2006-01-02 15:04:05")
- jsonByte, err := json.Marshal(info)
- if err != nil {
- log.Info(err.Error())
- return 0
- }
- db := database2.GetConnection()
- stmt, err := db.Prepare("INSERT INTO `goku_redis_info`(server,info,datetime) VALUES(?,?,?)")
- if err != nil {
- log.Info(err.Error())
- return 0
- }
- defer stmt.Close()
- ret, err := stmt.Exec(server, string(jsonByte), datetime)
- if err != nil {
- log.Info(err.Error())
- return 0
- }
- id, err := ret.LastInsertId()
- if err != nil {
- log.Info(err.Error())
- return 0
- }
- return id
-}
-
-func SaveServer(serverId string, password string, clusterId int, status int) {
- db := database2.GetConnection()
-
- stmt, err := db.Prepare("INSERT INTO `goku_redis_server`(`server`,`password`,`clusterId`,`status`) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE `password`=VALUES(`password`),`status` =VALUES(`status`)")
- if err != nil {
- log.Info(err.Error())
- return
- }
-
- defer stmt.Close()
- _, err = stmt.Exec(serverId, password, clusterId, status)
- if err != nil {
- log.Info(err.Error())
- return
- }
-}
-func RemoveServer(serverId string, clusterId int) {
- db := database2.GetConnection()
-
- stmt, err := db.Prepare("DELETE from `goku_redis_server` WHERE `server`=? and `clusterID` = ?;")
- if err != nil {
- log.Info(err.Error())
- return
- }
- defer stmt.Close()
- _, err = stmt.Exec(serverId, clusterId)
- if err != nil {
- log.Info(err.Error())
- return
- }
-}
-
-func GetRedisServerByStatus(status int) ([]*entity.RedisNode, error) {
- sql := "SELECT `server`,`clusterID` FROM `goku_redis_server` WHERE `status` = ?"
- smt, err := database2.GetConnection().Prepare(sql)
- if err != nil {
- return nil, err
- }
- rows, err := smt.Query(status)
- if err != nil {
- return nil, err
- }
- servers := make([]*entity.RedisNode, 0)
- for rows.Next() {
- node := new(entity.RedisNode)
- err := rows.Scan(&node.Server, &node.ClusterId)
- if err != nil {
- return nil, err
- }
- servers = append(servers, node)
- }
- return servers, nil
-}
-func GetServers(clusterId int) ([]*entity.RedisNode, error) {
+//GetServers 获取redis服务列表
+func GetServers(clusterID int) ([]*entity.RedisNode, error) {
db := database2.GetConnection()
- rows, err := db.Query("SELECT `server`,`password`,`clusterID` from `goku_redis_server` WHERE `clusterID`=?;", clusterId)
+ rows, err := db.Query("SELECT `server`,`password`,`clusterID` from `goku_redis_server` WHERE `clusterID`=?;", clusterID)
if err != nil {
return nil, err
}
@@ -132,7 +26,7 @@ func GetServers(clusterId int) ([]*entity.RedisNode, error) {
servers := make([]*entity.RedisNode, 0)
for rows.Next() {
node := new(entity.RedisNode)
- err := rows.Scan(&node.Server, &node.Password, &node.ClusterId)
+ err := rows.Scan(&node.Server, &node.Password, &node.ClusterID)
if err != nil {
return nil, err
@@ -142,67 +36,6 @@ func GetServers(clusterId int) ([]*entity.RedisNode, error) {
return servers, nil
}
-func SetRedisNodeStatus(server string, clusterId int, status int) {
- db := database2.GetConnection()
- stmt, err := db.Prepare("UPDATE `goku_redis_server` SET `status` = ? WHERE `server` = ? AND `clusterID`=?;")
- if err != nil {
- log.Info(err.Error())
- return
- }
-
- defer stmt.Close()
- _, err = stmt.Exec(status, server, clusterId)
- if err != nil {
- log.Info(err.Error())
- return
- }
-}
-
-func GetInfo(serverId string) (map[string]interface{}, error) {
- var info string
- db := database2.GetConnection()
- err := db.QueryRow("SELECT `info` FROM `goku_redis_info` WHERE server=? ORDER BY datetime DESC LIMIT 1", serverId).Scan(&info)
- if err != nil {
- log.Info(err.Error())
- return nil, err
- }
- jsonMap := make(map[string]interface{})
- jsonErr := json.Unmarshal([]byte(info), &jsonMap)
-
- if jsonErr != nil {
- log.Info(jsonErr.Error())
- return nil, jsonErr
- }
- return jsonMap, nil
-}
-
-func GetMemoryInfo(serverId, fromDate, toDate string) ([]map[string]interface{}, error) {
- db := database2.GetConnection()
- sql := "SELECT used,peak,datetime FROM `goku_redis_memory` WHERE server=? AND datetime>=? AND datetime<=?"
- rows, err := db.Query(sql, serverId, fromDate, toDate)
- if err != nil {
- log.Info(err.Error())
- return nil, err
- }
- defer rows.Close()
- var ret []map[string]interface{}
- for rows.Next() {
- var (
- used string
- peak string
- datetime string
- )
- if err := rows.Scan(&used, &peak, &datetime); err != nil {
- if err != io.EOF {
- log.Info(err.Error())
- }
- continue
- }
- ret = append(ret, map[string]interface{}{"used": used, "peak": peak, "datetime": datetime})
- }
- return ret, nil
-}
-
// GetRedisCount 获取redis数量
func GetRedisCount() (int, int) {
sql := "SELECT status,COUNT(*) FROM goku_redis_server GROUP BY status;"
@@ -227,6 +60,7 @@ func GetRedisCount() (int, int) {
return normalCount, errorCount
}
+//CreateTable 创建表
func CreateTable() error {
sqlDatas := []string{
diff --git a/server/dao/console-mysql/redis_test.go b/server/dao/console-mysql/redis_test.go
index 4511ac9..61e6c36 100644
--- a/server/dao/console-mysql/redis_test.go
+++ b/server/dao/console-mysql/redis_test.go
@@ -1 +1 @@
-package console_mysql
+package consolemysql
diff --git a/server/dao/console-mysql/script.go b/server/dao/console-mysql/script.go
index 7f91946..12a877c 100644
--- a/server/dao/console-mysql/script.go
+++ b/server/dao/console-mysql/script.go
@@ -1,15 +1,9 @@
-package console_mysql
+package consolemysql
import (
"encoding/json"
- log "github.com/eolinker/goku-api-gateway/goku-log"
- "strconv"
- "strings"
- "time"
-
- entity2 "github.com/eolinker/goku-api-gateway/server/entity/balance-entity"
-
database2 "github.com/eolinker/goku-api-gateway/common/database"
+ log "github.com/eolinker/goku-api-gateway/goku-log"
)
type balanceConfig struct {
@@ -21,63 +15,7 @@ type server struct {
Weight int `json:"weight"`
}
-func RefreshApiInfo() bool {
- db := database2.GetConnection()
- // 随机生成字符串
- sqlCode := `SELECT apiID,IFNULL(targetServer,"http://") FROM goku_gateway_api;`
- rows, err := db.Query(sqlCode)
- if err != nil {
- log.Error(err)
- return false
- }
- //延时关闭Rows
- defer rows.Close()
- //获取记录列
- if _, err = rows.Columns(); err != nil {
- log.Error(err)
- return false
- } else {
- Tx, _ := db.Begin()
- for rows.Next() {
- var apiID int
- var targetServer string
- err = rows.Scan(&apiID, &targetServer)
- if err != nil {
- Tx.Rollback()
- log.Error(err)
- return false
- }
- protocol := "http"
- balanceName := ""
- if len(targetServer) > 4 {
- arr := strings.Split(targetServer, "://")
- arrLen := len(arr)
- if arrLen > 1 {
- protocol, balanceName = arr[0], arr[1]
- } else {
- if arrLen == 1 {
- if arr[0] == "http" || arr[0] == "https" {
- protocol = arr[0]
- }
- }
- }
-
- }
- stripSlash := true
- _, err = Tx.Exec("UPDATE goku_gateway_api SET stripSlash = ?,protocol=?,balanceName=? WHERE apiID = ?", stripSlash, protocol, balanceName, apiID)
- if err != nil {
- Tx.Rollback()
- log.Error(err)
- return false
- }
- }
-
- Tx.Commit()
- return true
- }
-}
-
-// 新建项目
+// RefreshGatewayAlertConfig 新建项目
func RefreshGatewayAlertConfig() bool {
db := database2.GetConnection()
var (
@@ -148,66 +86,6 @@ func RefreshGatewayAlertConfig() bool {
return true
}
-// 新建项目
-func RefreshBalance(name string) bool {
- db := database2.GetConnection()
- // 获取网关告警配置
- sqlCode := "SELECT balanceID,IFNULL(balanceConfig,'') FROM goku_balance;"
- rows, err := db.Query(sqlCode)
- if err != nil {
- log.Error(err)
- return false
- }
- defer rows.Close()
- Tx, _ := db.Begin()
- for rows.Next() {
- var balanceConfigStr string
- var balanceID int
- err = rows.Scan(&balanceID, &balanceConfigStr)
- if err != nil {
- Tx.Rollback()
- log.Error(err)
- return false
- }
- var configs balanceConfig
- err = json.Unmarshal([]byte(balanceConfigStr), &configs)
- if err != nil {
- Tx.Rollback()
- log.Error(err)
- return false
- }
- staticOrg := ""
- for _, config := range configs.LoadBalancingServer {
- config.Server = strings.Replace(config.Server, " ", "", -1)
- if config.Server == "" {
- continue
- }
- weight := 1
- if config.Weight > 0 {
- weight = config.Weight
- }
-
- staticOrg += config.Server + " " + strconv.Itoa(weight) + ";"
- }
- defaultConfig := &entity2.BalanceConfig{
- ServersConfigOrg: staticOrg,
- }
- clusterConfig := make(map[string]*entity2.BalanceConfig)
- clusterConfig[name] = &entity2.BalanceConfig{}
- dcStr, _ := json.Marshal(defaultConfig)
- ccStr, _ := json.Marshal(clusterConfig)
- _, err = Tx.Exec("UPDATE goku_balance SET defaultConfig = ?,clusterConfig = ? WHERE balanceID = ?;", dcStr, ccStr, balanceID)
- if err != nil {
- Tx.Rollback()
- log.Error(err)
- return false
- }
- }
-
- Tx.Commit()
- return true
-}
-
type monitorRecord struct {
gatewayRequestCount int
gatewaySuccessCount int
@@ -225,58 +103,3 @@ type monitorRecord struct {
strategyID string
apiID int
}
-
-func RefreshMonitorRecord(clusterID int) bool {
- db := database2.GetConnection()
- // 获取网关告警配置
- // gatewayRecordSQL := "SELECT gatewayRequestCount,gatewaySuccessCount,gatewayStatus2xxCount,gatewayStatus4xxCount,gatewayStatus5xxCount,gatewayStatus5xxCount,proxySuccessCount,proxyStatus2xxCount,proxyStatus4xxCount,proxyStatus5xxCount,proxyTimeoutCount,updateTime FROM goku_gateway_request_record WHERE gatewayRequestCount > 0;"
- // apiRecordSQL := "SELECT apiID,gatewayRequestCount,gatewaySuccessCount,gatewayStatus2xxCount,gatewayStatus4xxCount,gatewayStatus5xxCount,gatewayStatus5xxCount,proxySuccessCount,proxyStatus2xxCount,proxyStatus4xxCount,proxyStatus5xxCount,proxyTimeoutCount,updateTime FROM goku_gateway_api_request_record WHERE gatewayRequestCount > 0;"
- strategyRecordSQL := "SELECT strategyID,gatewayRequestCount,gatewaySuccessCount,gatewayStatus2xxCount,gatewayStatus4xxCount,gatewayStatus5xxCount,proxyRequestCount,proxySuccessCount,proxyStatus2xxCount,proxyStatus4xxCount,proxyStatus5xxCount,proxyTimeoutCount,updateTime FROM goku_gateway_strategy_request_record WHERE gatewayRequestCount > 0;"
- monitorRecordSQL := "SELECT strategyID,apiID,gatewayRequestCount,gatewaySuccessCount,gatewayStatus2xxCount,gatewayStatus4xxCount,gatewayStatus5xxCount,proxyRequestCount,proxySuccessCount,proxyStatus2xxCount,proxyStatus4xxCount,proxyStatus5xxCount,proxyTimeoutCount,updateTime FROM goku_gateway_monitor_request_record WHERE gatewayRequestCount > 0 AND monitorType = 0;"
- rows, err := db.Query(strategyRecordSQL)
- if err != nil {
- log.Error(err)
- return false
- }
- timeTemplate1 := "2006-01-02 15:04:05"
- timeTemplate2 := "2006010215"
- defer rows.Close()
- records := make([]monitorRecord, 0)
- for rows.Next() {
- record := monitorRecord{}
- err := rows.Scan(&record.strategyID, &record.gatewayRequestCount, &record.gatewaySuccessCount, &record.gatewayStatus2xxCount, &record.gatewayStatus4xxCount, &record.gatewayStatus5xxCount, &record.proxyRequestCount, &record.proxySuccessCount, &record.proxyStatus2xxCount, &record.proxyStatus4xxCount, &record.proxyStatus5xxCount, &record.proxyTimeoutCount, &record.updateTime)
- if err != nil {
-
- log.Error(err)
- continue
- }
- stamp, _ := time.ParseInLocation(timeTemplate1, record.updateTime, time.Local)
- record.hour = stamp.Format(timeTemplate2)
- record.apiID = 0
- records = append(records, record)
- }
-
- rows, err = db.Query(monitorRecordSQL)
- if err != nil {
- log.Error(err)
- return false
- }
- for rows.Next() {
- record := monitorRecord{}
- err := rows.Scan(&record.strategyID, &record.apiID, &record.gatewayRequestCount, &record.gatewaySuccessCount, &record.gatewayStatus2xxCount, &record.gatewayStatus4xxCount, &record.gatewayStatus5xxCount, &record.proxyRequestCount, &record.proxySuccessCount, &record.proxyStatus2xxCount, &record.proxyStatus4xxCount, &record.proxyStatus5xxCount, &record.proxyTimeoutCount, &record.updateTime)
- if err != nil {
- log.Error(err)
- continue
- }
- stamp, _ := time.ParseInLocation(timeTemplate1, record.updateTime, time.Local)
- record.hour = stamp.Format(timeTemplate2)
- records = append(records, record)
- }
- Tx, _ := db.Begin()
- refreshSQL := "INSERT INTO goku_monitor_cluster (strategyID,apiID,gatewayRequestCount,gatewaySuccessCount,gatewayStatus2xxCount,gatewayStatus4xxCount,gatewayStatus5xxCount,proxyRequestCount,proxySuccessCount,proxyStatus2xxCount,proxyStatus4xxCount,proxyStatus5xxCount,proxyTimeoutCount,updateTime,clusterID,hour) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
- for _, record := range records {
- Tx.Exec(refreshSQL, record.strategyID, record.apiID, record.gatewayRequestCount, record.gatewaySuccessCount, record.gatewayStatus2xxCount, record.gatewayStatus4xxCount, record.gatewayStatus5xxCount, record.proxyRequestCount, record.proxySuccessCount, record.proxyStatus2xxCount, record.proxyStatus4xxCount, record.proxyStatus5xxCount, record.proxyTimeoutCount, record.updateTime, clusterID, record.hour)
- }
- Tx.Commit()
- return true
-}
diff --git a/server/dao/console-mysql/strategy.go b/server/dao/console-mysql/strategy.go
index f35ddf3..fc7e7b7 100644
--- a/server/dao/console-mysql/strategy.go
+++ b/server/dao/console-mysql/strategy.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
"fmt"
@@ -10,7 +10,7 @@ import (
"github.com/eolinker/goku-api-gateway/utils"
)
-// 新增策略组
+//AddStrategy 新增策略组
func AddStrategy(strategyName string, groupID int) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -38,12 +38,11 @@ func AddStrategy(strategyName string, groupID int) (bool, string, error) {
_, err = stmt.Exec(strategyID, strategyName, now, now, groupID)
if err != nil {
return false, "[ERROR]Failed to insert data!", err
- } else {
- return true, strategyID, nil
}
+ return true, strategyID, nil
}
-// 修改策略组信息
+//EditStrategy 修改策略组信息
func EditStrategy(strategyID, strategyName string, groupID int) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -55,12 +54,11 @@ func EditStrategy(strategyID, strategyName string, groupID int) (bool, string, e
_, err = stmt.Exec(strategyName, groupID, now, strategyID)
if err != nil {
return false, "[ERROR]Failed to update data!", err
- } else {
- return true, strategyID, nil
}
+ return true, strategyID, nil
}
-// 删除策略组
+//DeleteStrategy 删除策略组
func DeleteStrategy(strategyID string) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
@@ -153,7 +151,7 @@ func GetOpenStrategy() (bool, *entity.Strategy, error) {
return true, &openStrategy, nil
}
-// 获取策略组信息
+//GetStrategyInfo 获取策略组信息
func GetStrategyInfo(strategyID string) (bool, *entity.Strategy, error) {
db := database2.GetConnection()
sql := `SELECT strategyID,strategyName,IFNULL(updateTime,''),strategyType,enableStatus FROM goku_gateway_strategy WHERE strategyID = ?;`
@@ -161,12 +159,11 @@ func GetStrategyInfo(strategyID string) (bool, *entity.Strategy, error) {
err := db.QueryRow(sql, strategyID).Scan(&strategy.StrategyID, &strategy.StrategyName, &strategy.UpdateTime, &strategy.StrategyType, &strategy.EnableStatus)
if err != nil {
return false, nil, err
- } else {
- return true, strategy, err
}
+ return true, strategy, err
}
-// 检查策略组ID是否存在
+// CheckStrategyIsExist 检查策略组ID是否存在
func CheckStrategyIsExist(strategyID string) (bool, error) {
db := database2.GetConnection()
sql := "SELECT strategyID FROM goku_gateway_strategy WHERE strategyID = ?;"
@@ -174,12 +171,11 @@ func CheckStrategyIsExist(strategyID string) (bool, error) {
err := db.QueryRow(sql, strategyID).Scan(&id)
if err != nil {
return false, err
- } else {
- return true, err
}
+ return true, err
}
-// 批量修改策略组分组
+// BatchEditStrategyGroup 批量修改策略组分组
func BatchEditStrategyGroup(strategyIDList string, groupID int) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -202,7 +198,7 @@ func BatchEditStrategyGroup(strategyIDList string, groupID int) (bool, string, e
return true, "", nil
}
-// 批量修改策略组
+// BatchDeleteStrategy 批量修改策略组
func BatchDeleteStrategy(strategyIDList string) (bool, string, error) {
db := database2.GetConnection()
Tx, _ := db.Begin()
@@ -250,6 +246,7 @@ func BatchDeleteStrategy(strategyIDList string) (bool, string, error) {
return true, "", nil
}
+//CheckIsOpenStrategy 判断是否是开放策略
func CheckIsOpenStrategy(strategyID string) bool {
db := database2.GetConnection()
var strategyType int
@@ -260,12 +257,11 @@ func CheckIsOpenStrategy(strategyID string) bool {
}
if strategyType == 1 {
return true
- } else {
- return false
}
+ return false
}
-// 更新策略启动状态
+// BatchUpdateStrategyEnableStatus 更新策略启动状态
func BatchUpdateStrategyEnableStatus(strategyIDList string, enableStatus int) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
diff --git a/server/dao/console-mysql/strategyGroup.go b/server/dao/console-mysql/strategyGroup.go
index 91143de..327a4f6 100644
--- a/server/dao/console-mysql/strategyGroup.go
+++ b/server/dao/console-mysql/strategyGroup.go
@@ -1,11 +1,10 @@
-package console_mysql
+package consolemysql
import (
database2 "github.com/eolinker/goku-api-gateway/common/database"
- log "github.com/eolinker/goku-api-gateway/goku-log"
)
-// 新建策略组分组
+//AddStrategyGroup 新建策略组分组
func AddStrategyGroup(groupName string) (bool, interface{}, error) {
db := database2.GetConnection()
sql := "INSERT INTO goku_gateway_strategy_group (groupName) VALUES (?);"
@@ -25,7 +24,7 @@ func AddStrategyGroup(groupName string) (bool, interface{}, error) {
return true, groupID, nil
}
-// 修改策略组分组
+//EditStrategyGroup 修改策略组分组
func EditStrategyGroup(groupName string, groupID int) (bool, string, error) {
db := database2.GetConnection()
sql := "UPDATE goku_gateway_strategy_group SET groupName = ? WHERE groupID = ?;"
@@ -41,7 +40,7 @@ func EditStrategyGroup(groupName string, groupID int) (bool, string, error) {
return true, "", nil
}
-// 删除策略组分组
+//DeleteStrategyGroup 删除策略组分组
func DeleteStrategyGroup(groupID int) (bool, string, error) {
db := database2.GetConnection()
// 查询该分组下所有策略组ID
@@ -54,17 +53,14 @@ func DeleteStrategyGroup(groupID int) (bool, string, error) {
//延时关闭Rows
defer rows.Close()
//获取记录列
- if _, err = rows.Columns(); err != nil {
- return false, "[ERROR]Illegal SQL statement!", err
- } else {
- for rows.Next() {
- var strategyID string
- err = rows.Scan(&strategyID)
- if err != nil {
- return false, "[ERROR]Fail to excute SQL statement!", err
- }
- strategyIDList = append(strategyIDList, strategyID)
+
+ for rows.Next() {
+ var strategyID string
+ err = rows.Scan(&strategyID)
+ if err != nil {
+ return false, "[ERROR]Fail to excute SQL statement!", err
}
+ strategyIDList = append(strategyIDList, strategyID)
}
Tx, _ := db.Begin()
_, err = Tx.Exec("DELETE FROM goku_gateway_strategy_group WHERE groupID = ?;", groupID)
@@ -111,7 +107,7 @@ func DeleteStrategyGroup(groupID int) (bool, string, error) {
return true, "", nil
}
-// 获取策略组分组列表
+//GetStrategyGroupList 获取策略组分组列表
func GetStrategyGroupList() (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
sql := "SELECT groupID,groupName,groupType FROM goku_gateway_strategy_group WHERE groupType = 0;"
@@ -121,29 +117,26 @@ func GetStrategyGroupList() (bool, []map[string]interface{}, error) {
}
defer rows.Close()
//获取记录列
- if _, err = rows.Columns(); err != nil {
- log.Info(err.Error())
- return false, nil, err
- } else {
- groupList := make([]map[string]interface{}, 0)
- for rows.Next() {
- var groupID, groupType int
- var groupName string
- err = rows.Scan(&groupID, &groupName, &groupType)
- if err != nil {
- return false, nil, err
- }
- groupInfo := map[string]interface{}{
- "groupID": groupID,
- "groupName": groupName,
- }
- groupList = append(groupList, groupInfo)
+ groupList := make([]map[string]interface{}, 0)
+ for rows.Next() {
+ var groupID, groupType int
+ var groupName string
+ err = rows.Scan(&groupID, &groupName, &groupType)
+ if err != nil {
+ return false, nil, err
}
- return true, groupList, nil
+
+ groupInfo := map[string]interface{}{
+ "groupID": groupID,
+ "groupName": groupName,
+ }
+ groupList = append(groupList, groupInfo)
}
+ return true, groupList, nil
}
+//CheckIsOpenGroup 检查是否是开放分组
func CheckIsOpenGroup(groupID int) bool {
db := database2.GetConnection()
var groupType int
@@ -154,7 +147,6 @@ func CheckIsOpenGroup(groupID int) bool {
}
if groupType == 1 {
return true
- } else {
- return false
}
+ return false
}
diff --git a/server/dao/console-mysql/strategyPlugin.go b/server/dao/console-mysql/strategyPlugin.go
index 4816aee..11ae0b4 100644
--- a/server/dao/console-mysql/strategyPlugin.go
+++ b/server/dao/console-mysql/strategyPlugin.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
SQL "database/sql"
@@ -14,7 +14,7 @@ import (
var strategyPlugins = []string{"goku-oauth2_auth", "goku-rate_limiting", "goku-replay_attack_defender"}
-// 新增策略组插件
+//AddPluginToStrategy 新增策略组插件
func AddPluginToStrategy(pluginName, config, strategyID string) (bool, interface{}, error) {
db := database2.GetConnection()
// 查询接口是否添加该插件
@@ -47,7 +47,7 @@ func AddPluginToStrategy(pluginName, config, strategyID string) (bool, interface
return true, connID, nil
}
-// 新增策略组插件配置
+//EditStrategyPluginConfig 新增策略组插件配置
func EditStrategyPluginConfig(pluginName, config, strategyID string) (bool, string, error) {
db := database2.GetConnection()
// 查询策略组是否添加该插件
@@ -125,7 +125,7 @@ func GetStrategyPluginList(strategyID, keyword string, condition int) (bool, []m
return true, pluginList, nil
}
-// 通过策略组ID获取配置信息
+//GetStrategyPluginConfig 通过策略组ID获取配置信息
func GetStrategyPluginConfig(strategyID, pluginName string) (bool, string, error) {
db := database2.GetConnection()
sql := "SELECT pluginConfig FROM goku_conn_plugin_strategy WHERE strategyID = ? AND pluginName = ?;"
@@ -134,16 +134,13 @@ func GetStrategyPluginConfig(strategyID, pluginName string) (bool, string, error
if err != nil {
if err == SQL.ErrNoRows {
return false, "", errors.New("[ERROR]Can not find the plugin")
- } else {
- return false, "", err
}
-
- } else {
- return true, p, nil
+ return false, "", err
}
+ return true, p, nil
}
-// 检查策略组是否绑定插件
+//CheckPluginIsExistInStrategy 检查策略组是否绑定插件
func CheckPluginIsExistInStrategy(strategyID, pluginName string) (bool, error) {
db := database2.GetConnection()
sql := "SELECT strategyID FROM goku_conn_plugin_strategy WHERE strategyID = ? AND pluginName = ?;"
@@ -151,12 +148,11 @@ func CheckPluginIsExistInStrategy(strategyID, pluginName string) (bool, error) {
err := db.QueryRow(sql, strategyID, pluginName).Scan(&id)
if err != nil {
return false, err
- } else {
- return true, err
}
+ return true, err
}
-// 检查策略组插件是否开启
+//GetStrategyPluginStatus 检查策略组插件是否开启
func GetStrategyPluginStatus(strategyID, pluginName string) (bool, error) {
db := database2.GetConnection()
sql := "SELECT pluginStatus FROM goku_conn_plugin_strategy WHERE strategyID = ? AND pluginName = ?;"
@@ -164,15 +160,14 @@ func GetStrategyPluginStatus(strategyID, pluginName string) (bool, error) {
err := db.QueryRow(sql, strategyID, pluginName).Scan(&pluginStatus)
if err != nil {
return false, err
- } else {
- if pluginStatus != 1 {
- return false, nil
- }
- return true, nil
}
+ if pluginStatus != 1 {
+ return false, nil
+ }
+ return true, nil
}
-// 获取Connid
+// GetConnIDFromStrategyPlugin 获取ConnID
func GetConnIDFromStrategyPlugin(pluginName, strategyID string) (bool, int, error) {
db := database2.GetConnection()
sql := "SELECT connID FROM goku_conn_plugin_strategy WHERE strategyID = ? AND pluginName = ?;"
@@ -180,12 +175,11 @@ func GetConnIDFromStrategyPlugin(pluginName, strategyID string) (bool, int, erro
err := db.QueryRow(sql, strategyID, pluginName).Scan(&connID)
if err != nil {
return false, 0, err
- } else {
- return true, connID, nil
}
+ return true, connID, nil
}
-// 批量修改策略组插件状态
+//BatchEditStrategyPluginStatus 批量修改策略组插件状态
func BatchEditStrategyPluginStatus(connIDList, strategyID string, pluginStatus int) (bool, string, error) {
db := database2.GetConnection()
t := time.Now()
@@ -209,7 +203,7 @@ func BatchEditStrategyPluginStatus(connIDList, strategyID string, pluginStatus i
return true, "", nil
}
-// 批量删除策略组插件
+//BatchDeleteStrategyPlugin 批量删除策略组插件
func BatchDeleteStrategyPlugin(connIDList, strategyID string) (bool, string, error) {
db := database2.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
@@ -231,7 +225,7 @@ func BatchDeleteStrategyPlugin(connIDList, strategyID string) (bool, string, err
return true, "", nil
}
-// 通过connIDList判断插件是否存在
+//CheckStrategyPluginIsExistByConnIDList 通过connIDList判断插件是否存在
func CheckStrategyPluginIsExistByConnIDList(connIDList, pluginName string) (bool, error) {
db := database2.GetConnection()
sql := "SELECT pluginStatus FROM goku_conn_plugin_strategy WHERE connID IN (" + connIDList + ") AND pluginName = ?;"
@@ -239,11 +233,11 @@ func CheckStrategyPluginIsExistByConnIDList(connIDList, pluginName string) (bool
err := db.QueryRow(sql, pluginName).Scan(&pluginStatus)
if err != nil {
return false, err
- } else {
- return true, nil
}
+ return true, nil
}
+//UpdateStrategyTagByPluginName 更新策略插件标志位
func UpdateStrategyTagByPluginName(strategyID string, pluginNameList string) error {
db := database2.GetConnection()
plugins := strings.Split(pluginNameList, ",")
@@ -264,6 +258,7 @@ func UpdateStrategyTagByPluginName(strategyID string, pluginNameList string) err
return nil
}
+//BatchUpdateStrategyPluginUpdateTag 批量更新策略插件更新标志位
func BatchUpdateStrategyPluginUpdateTag(strategyIDList string) error {
db := database2.GetConnection()
strategyIDs := strings.Split(strategyIDList, ",")
@@ -290,19 +285,12 @@ func BatchUpdateStrategyPluginUpdateTag(strategyIDList string) error {
return nil
}
+//UpdateAllStrategyPluginUpdateTag 更新策略插件更新标志位
func UpdateAllStrategyPluginUpdateTag() error {
db := database2.GetConnection()
- // code := make([]string, 0, len(strategyPlugins))
updateTag := time.Now().Format("20060102150405")
- // s := make([]interface{}, 0, len(strategyPlugins)+1)
- // s = append(s, updateTag)
- // for i := 0; i < len(strategyPlugins); i++ {
- // code = append(code, "?")
- // s = append(s, strategyPlugins[i])
- // }
- // sql := "UPDATE goku_conn_plugin_strategy SET updateTag = ? WHERE pluginName IN (" + strings.Join(code, ",") + ");"
+
sql := "UPDATE goku_conn_plugin_strategy SET updateTag = ?;"
- // _, err := db.Exec(sql, s...)
_, err := db.Exec(sql, updateTag)
if err != nil {
return err
diff --git a/server/dao/console-mysql/user.go b/server/dao/console-mysql/user.go
index 61d1de7..47db458 100644
--- a/server/dao/console-mysql/user.go
+++ b/server/dao/console-mysql/user.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
"encoding/json"
@@ -7,9 +7,9 @@ import (
"github.com/eolinker/goku-api-gateway/utils"
)
-type permissionsJson map[string]bool
+type permissionsJSON map[string]bool
-// 修改账户信息
+//EditPassword 修改账户信息
func EditPassword(oldPassword, newPassword string, userID int) (bool, string, error) {
db := database2.GetConnection()
// 查询旧密码是否存在
@@ -19,7 +19,7 @@ func EditPassword(oldPassword, newPassword string, userID int) (bool, string, er
sql := "SELECT loginCall,loginPassword FROM goku_admin WHERE loginPassword = ? AND userID = ?;"
err := db.QueryRow(sql, oldPassword, userID).Scan(&loginCall, &password)
if err != nil {
- return false, "[ERROR]Old password error!", err
+ return false, "[error]old password error!", err
}
sql = "UPDATE goku_admin SET loginPassword = ? WHERE loginPassword = ? AND userID = ?;"
@@ -39,7 +39,7 @@ func EditPassword(oldPassword, newPassword string, userID int) (bool, string, er
return true, loginCall, nil
}
-// 获取账户信息
+// GetUserInfo 获取账户信息
func GetUserInfo(userID int) (bool, interface{}, error) {
db := database2.GetConnection()
sql := `SELECT loginCall,IFNULL(remark,""),IFNULL(permissions,""),userType FROM goku_admin WHERE userID = ?;`
@@ -47,7 +47,7 @@ func GetUserInfo(userID int) (bool, interface{}, error) {
var userType int
err := db.QueryRow(sql, userID).Scan(&loginCall, &remark, &permissions, &userType)
if err != nil {
- return false, "[ERROR]This user does not exist!", err
+ return false, "[error]this user does not exist!", err
}
var perssionMap map[string]interface{}
if permissions == "" {
@@ -67,42 +67,43 @@ func GetUserInfo(userID int) (bool, interface{}, error) {
return true, userInfo, nil
}
-// 获取用户类型
+// GetUserType 获取用户类型
func GetUserType(userID int) (bool, interface{}, error) {
db := database2.GetConnection()
sql := "SELECT userType FROM goku_admin WHERE userID = ?;"
var userType int
err := db.QueryRow(sql, userID).Scan(&userType)
if err != nil {
- return false, "[ERROR]This user does not exist!", err
+ return false, "[error]this user does not exist!", err
}
return true, userType, nil
}
-// 判断是否是管理员
+// CheckUserIsAdmin 判断是否是管理员
func CheckUserIsAdmin(userID int) (bool, string, error) {
db := database2.GetConnection()
sql := "SELECT userType FROM goku_admin WHERE userID = ? AND (userType = 0 OR userType = 1);"
var userType int
err := db.QueryRow(sql, userID).Scan(&userType)
if err != nil {
- return false, "[ERROR]This user is not admin!", errors.New("[ERROR]This user is not admin!")
+ return false, "[error]this user is not admin!", errors.New("[error]this user is not admin")
}
return true, "", nil
}
-// 判断是否是超级管理员
+//CheckUserIsSuperAdmin 判断是否是超级管理员
func CheckUserIsSuperAdmin(userID int) (bool, string, error) {
db := database2.GetConnection()
sql := "SELECT userType FROM goku_admin WHERE userID = ? AND userType = 0;"
var userType int
err := db.QueryRow(sql, userID).Scan(&userType)
if err != nil {
- return false, "[ERROR]This user is not super admin!", errors.New("[ERROR]This user is not super admin!")
+ return false, "[error]this user is not super admin!", errors.New("[error]this user is not super admin")
}
return true, "", nil
}
+//CheckSuperAdminCount 获取超级管理员数量
func CheckSuperAdminCount() (int, error) {
db := database2.GetConnection()
sql := "SELECT count(*) FROM goku_admin WHERE userType = 0;"
@@ -115,7 +116,7 @@ func CheckSuperAdminCount() (int, error) {
return count, nil
}
-// 检查用户权限
+// CheckUserPermission 检查用户权限
func CheckUserPermission(operationType, operation string, userID int) (bool, string, error) {
db := database2.GetConnection()
var permissions string
@@ -123,35 +124,31 @@ func CheckUserPermission(operationType, operation string, userID int) (bool, str
sql := `SELECT userType,IFNULL(permissions,"") FROM goku_admin WHERE userID = ?;`
err := db.QueryRow(sql, userID).Scan(&userType, &permissions)
if err != nil {
- return false, "[ERROR]This user does not exist!", err
+ return false, "[error]this user does not exist!", err
}
if userType == 0 || userType == 1 {
return true, "", nil
}
if permissions == "" {
- return false, "[ERROR]This user does not assigned permission", nil
+ return false, "[error]this user does not assigned permission", nil
}
- permissionsMap := make(map[string]permissionsJson)
+ permissionsMap := make(map[string]permissionsJSON)
err = json.Unmarshal([]byte(permissions), &permissionsMap)
if err != nil {
return false, "[ERROR]Fail to parse json!!", err
}
if value, ok := permissionsMap[operationType]; !ok {
- return false, "[ERROR]Operation type does not exist!", nil
- } else {
- if v, temp := value[operation]; !temp {
- return false, "[ERROR]Operation does not exist!!", nil
- } else {
- if !v {
- return false, "[ERROR]No permissions!", nil
- } else {
- return true, "", nil
- }
- }
+ return false, "[error]operation type does not exist!", nil
+ } else if v, temp := value[operation]; !temp {
+ return false, "[error]operation does not exist!!", nil
+ } else if !v {
+
+ return false, "[ERROR]No permissions!", nil
}
+ return true, "", nil
}
-// 获取具有编辑权限的用户列表
+// GetUserListWithPermission 获取具有编辑权限的用户列表
func GetUserListWithPermission(operationType, operation string) (bool, []map[string]interface{}, error) {
db := database2.GetConnection()
sql := `SELECT userID,IF(remark IS NULL OR remark = "",loginCall,remark) as userName,userType,IFNULL(permissions,"") FROM goku_admin ORDER BY userType ASC;`
@@ -161,46 +158,39 @@ func GetUserListWithPermission(operationType, operation string) (bool, []map[str
}
defer rows.Close()
userList := make([]map[string]interface{}, 0)
- if _, err = rows.Columns(); err != nil {
- return false, make([]map[string]interface{}, 0), err
- } else {
- for rows.Next() {
- var (
- permissions string
- userType int
- userID int
- userName string
- )
- err = rows.Scan(&userID, &userName, &userType, &permissions)
+
+ for rows.Next() {
+ var (
+ permissions string
+ userType int
+ userID int
+ userName string
+ )
+ err = rows.Scan(&userID, &userName, &userType, &permissions)
+ if err != nil {
+ return false, make([]map[string]interface{}, 0), err
+ }
+ if userType != 0 && userType != 1 {
+ if permissions == "" {
+ continue
+ }
+ permissionsMap := make(map[string]permissionsJSON)
+ err = json.Unmarshal([]byte(permissions), &permissionsMap)
if err != nil {
return false, make([]map[string]interface{}, 0), err
}
- if userType != 0 && userType != 1 {
- if permissions == "" {
- continue
- }
- permissionsMap := make(map[string]permissionsJson)
- err = json.Unmarshal([]byte(permissions), &permissionsMap)
- if err != nil {
- return false, make([]map[string]interface{}, 0), err
- }
- if value, ok := permissionsMap[operationType]; !ok {
- return false, make([]map[string]interface{}, 0), errors.New("[ERROR]Operation type does not exist!")
- } else {
- if v, temp := value[operation]; !temp {
- return false, make([]map[string]interface{}, 0), errors.New("[ERROR]Operation does not exist!")
- } else {
- if !v {
- continue
- }
- }
- }
+ if value, ok := permissionsMap[operationType]; !ok {
+ return false, make([]map[string]interface{}, 0), errors.New("[error]operation type does not exist")
+ } else if v, temp := value[operation]; !temp {
+ return false, make([]map[string]interface{}, 0), errors.New("[error]operation does not exist")
+ } else if !v {
+ continue
}
- userList = append(userList, map[string]interface{}{
- "userID": userID,
- "userName": userName,
- })
}
+ userList = append(userList, map[string]interface{}{
+ "userID": userID,
+ "userName": userName,
+ })
}
return true, userList, nil
}
diff --git a/server/dao/console-mysql/utils.go b/server/dao/console-mysql/utils.go
index 47e0a9f..c89bcc1 100644
--- a/server/dao/console-mysql/utils.go
+++ b/server/dao/console-mysql/utils.go
@@ -1,4 +1,4 @@
-package console_mysql
+package consolemysql
import (
SQL "database/sql"
diff --git a/server/dao/dao-balance/add.go b/server/dao/dao-balance/add.go
index 7090820..3a28741 100644
--- a/server/dao/dao-balance/add.go
+++ b/server/dao/dao-balance/add.go
@@ -1,9 +1,10 @@
-package dao_balance
+package daobalance
import (
"github.com/eolinker/goku-api-gateway/common/database"
)
+//Add 新增负载
func Add(name, serviceName, desc, appName, static, staticCluster, now string) (string, error) {
//const sql = "INSERT INTO goku_balance (`balanceName`,`serviceName`,`appName`,`balanceDesc`,`static`,`staticCluster`,`createTime`,`updateTime`) VALUES (?,?,?,?,?,?,?,?,);"
@@ -20,6 +21,8 @@ func Add(name, serviceName, desc, appName, static, staticCluster, now string) (s
//}
return "", nil
}
+
+//AddStatic 新增静态
func AddStatic(name, serviceName, static, staticCluster, desc, now string) (string, error) {
const sql = "INSERT INTO goku_balance (`balanceName`,`serviceName`,`static`,`staticCluster`,`balanceDesc`,`createTime`,`updateTime`,`appName`,`defaultConfig`,`clusterConfig`,`balanceConfig`) VALUES (?,?,?,?,?,?,?,'','','','');"
@@ -36,6 +39,8 @@ func AddStatic(name, serviceName, static, staticCluster, desc, now string) (stri
}
return "", nil
}
+
+//AddDiscovery 新增服务发现
func AddDiscovery(name, serviceName, appName, desc, now string) (string, error) {
const sql = "INSERT INTO goku_balance (`balanceName`,`serviceName`,`appName`,`balanceDesc`,`createTime`,`updateTime`,`static`,`staticCluster`,`defaultConfig`,`clusterConfig`,`balanceConfig`) VALUES (?,?,?,?,?,?,'','','','','');"
@@ -52,6 +57,8 @@ func AddDiscovery(name, serviceName, appName, desc, now string) (string, error)
}
return "", nil
}
+
+//SaveStatic 保存静态
func SaveStatic(name, serviceName, static, staticCluster, desc string, now string) (string, error) {
const sql = "UPDATE `goku_balance` SET `serviceName`=? ,`static` = ?,`staticCluster`=?,`balanceDesc` =?,`updateTime`=? WHERE `balanceName`=?;"
db := database.GetConnection()
@@ -66,6 +73,8 @@ func SaveStatic(name, serviceName, static, staticCluster, desc string, now strin
}
return "", nil
}
+
+//SaveDiscover 保存服务发现
func SaveDiscover(name, serviceName, appName, desc string, now string) (string, error) {
const sql = "UPDATE `goku_balance` SET `serviceName`=? ,`appName` = ?,`balanceDesc` =?,`updateTime`=? WHERE `balanceName`=?;"
db := database.GetConnection()
@@ -80,6 +89,8 @@ func SaveDiscover(name, serviceName, appName, desc string, now string) (string,
}
return "", nil
}
+
+//Save 保存
func Save(name, desc, static, staticCluster, now string) (string, error) {
//const sql = "UPDATE `goku_balance` SET `balanceDesc` = ?,`static` =?,`staticCluster`=?,`updateTime`=? WHERE `balanceName` = ?;"
//
@@ -96,6 +107,7 @@ func Save(name, desc, static, staticCluster, now string) (string, error) {
return "", nil
}
+//Delete 删除
func Delete(name string) (string, error) {
const sql = "DELETE FROM `goku_balance` WHERE `balanceName`= ?;"
db := database.GetConnection()
@@ -111,7 +123,7 @@ func Delete(name string) (string, error) {
}
-// 批量删除负载
+//BatchDelete 批量删除负载
func BatchDelete(balanceNames []string) (string, error) {
db := database.GetConnection()
sql := "DELETE FROM `goku_balance` WHERE `balanceName` = ?;"
diff --git a/server/dao/dao-balance/balance.go b/server/dao/dao-balance/balance.go
index 5b09b2d..d1eae35 100644
--- a/server/dao/dao-balance/balance.go
+++ b/server/dao/dao-balance/balance.go
@@ -1,9 +1,10 @@
-package dao_balance
+package daobalance
import (
"github.com/eolinker/goku-api-gateway/common/database"
)
+//GetBalanceNames 获取负载名称列表
func GetBalanceNames() (bool, []string, error) {
db := database.GetConnection()
sql := "SELECT balanceName FROM goku_balance ;"
diff --git a/server/dao/dao-balance/get.go b/server/dao/dao-balance/get.go
index ad00404..9001c28 100644
--- a/server/dao/dao-balance/get.go
+++ b/server/dao/dao-balance/get.go
@@ -1,4 +1,4 @@
-package dao_balance
+package daobalance
import (
"fmt"
@@ -7,6 +7,7 @@ import (
"strings"
)
+//Get 获取负载信息
func Get(name string) (*entity.Balance, error) {
const sql = "SELECT A.`balanceName`,A.`serviceName`,IFNULL(B.`driver`,''),A.`appName`,IFNULL(A.`static`,''),IFNULL(A.`staticCluster`,''),A.`balanceDesc`,A.`updateTime`,A.`createTime` FROM `goku_balance` A LEFT JOIN `goku_service_config` B ON A.`serviceName` = B.`NAME` WHERE A.`balanceName`= ?;"
db := database.GetConnection()
@@ -19,6 +20,7 @@ func Get(name string) (*entity.Balance, error) {
return v.Type(), nil
}
+//GetAll 获取负载列表
func GetAll() ([]*entity.Balance, error) {
const sql = "SELECT A.`balanceName`,A.`serviceName`,IFNULL(B.`driver`,''),A.`appName`,IFNULL(A.`static`,''),IFNULL(A.`staticCluster`,''),A.`balanceDesc`,A.`updateTime`,A.`createTime` FROM `goku_balance` A LEFT JOIN `goku_service_config` B ON A.`serviceName` = B.`name` ORDER BY `updateTime` DESC;"
db := database.GetConnection()
@@ -40,6 +42,7 @@ func GetAll() ([]*entity.Balance, error) {
return r, nil
}
+//Search 查询
func Search(keyword string) ([]*entity.Balance, error) {
const sqlTpl = "SELECT A.`balanceName`,A.`serviceName`,IFNULL(B.`driver`,''),A.`appName`,IFNULL(A.`static`,''),IFNULL(A.`staticCluster`,''),A.`balanceDesc`,A.`updateTime`,A.`createTime` FROM `goku_balance` A LEFT JOIN `goku_service_config` B ON A.`serviceName` = B.`name` %s ORDER BY `updateTime` DESC;"
diff --git a/server/dao/node-mysql/dao-api/api.go b/server/dao/node-mysql/dao-api/api.go
index 97251c4..b09558e 100644
--- a/server/dao/node-mysql/dao-api/api.go
+++ b/server/dao/node-mysql/dao-api/api.go
@@ -1,4 +1,4 @@
-package dao_api
+package daoapi
import (
"fmt"
@@ -6,8 +6,8 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
-// 获取API接口列表
-func GetAllApi() (map[int]*entity.Api, error) {
+// GetAllAPI 获取API接口列表
+func GetAllAPI() (map[int]*entity.API, error) {
sql := "SELECT `apiID`,`apiName`,`requestMethod`,`requestURL`,`protocol`,`balanceName`,`targetURL`,`targetMethod`,`isFollow`,`stripPrefix`,`stripSlash`,`timeout`,`retryCount`,`alertValve` FROM `goku_gateway_api` ORDER BY `apiID` asc;"
stmt, e := database.GetConnection().Prepare(sql)
@@ -20,14 +20,14 @@ func GetAllApi() (map[int]*entity.Api, error) {
return nil, err
}
defer rows.Close()
- apiList := make(map[int]*entity.Api, 0)
+ apiList := make(map[int]*entity.API, 0)
//获取记录列
if _, err = rows.Columns(); err != nil {
return nil, err
}
for rows.Next() {
- api := new(entity.Api)
- err = rows.Scan(&api.ApiID, &api.ApiName, &api.RequestMethod, &api.RequestURL, &api.Protocol, &api.BalanceName, &api.TargetURL, &api.TargetMethod, &api.IsFollow, &api.StripPrefix, &api.StripSlash, &api.Timeout, &api.RetryCount, &api.AlertValve)
+ api := new(entity.API)
+ err = rows.Scan(&api.APIID, &api.APIName, &api.RequestMethod, &api.RequestURL, &api.Protocol, &api.BalanceName, &api.TargetURL, &api.TargetMethod, &api.IsFollow, &api.StripPrefix, &api.StripSlash, &api.Timeout, &api.RetryCount, &api.AlertValve)
if err != nil {
continue
}
@@ -38,7 +38,7 @@ func GetAllApi() (map[int]*entity.Api, error) {
api.TargetURL = fmt.Sprint("/", api.TargetURL)
}
- apiList[api.ApiID] = api
+ apiList[api.APIID] = api
}
return apiList, nil
diff --git a/server/dao/node-mysql/dao-balance/balance.go b/server/dao/node-mysql/dao-balance/balance.go
index 94c66e9..312958f 100644
--- a/server/dao/node-mysql/dao-balance/balance.go
+++ b/server/dao/node-mysql/dao-balance/balance.go
@@ -1,10 +1,11 @@
-package dao_balance
+package daobalance
import (
"github.com/eolinker/goku-api-gateway/common/database"
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
+//GetAllBalance 获取负载列表
func GetAllBalance() ([]*entity.Balance, error) {
const sql = "SELECT A.`balanceName`,A.`serviceName`,IFNULL(B.`driver`,''),A.`appName`,IFNULL(A.`static`,''),IFNULL(A.`staticCluster`,'') FROM `goku_balance` A LEFT JOIN `goku_service_config` B ON A.`serviceName` = B.`name`;"
db := database.GetConnection()
diff --git a/server/dao/node-mysql/dao-gateway/gateway.go b/server/dao/node-mysql/dao-gateway/gateway.go
index ceeaeaa..cf90e64 100644
--- a/server/dao/node-mysql/dao-gateway/gateway.go
+++ b/server/dao/node-mysql/dao-gateway/gateway.go
@@ -1,8 +1,8 @@
-package dao_gateway
+package daogateway
import "github.com/eolinker/goku-api-gateway/common/database"
-// 获取网关成功状态码
+//GetGatewayBaseInfo 获取网关成功状态码
func GetGatewayBaseInfo() (string, int) {
db := database.GetConnection()
var successCode string
@@ -15,7 +15,7 @@ func GetGatewayBaseInfo() (string, int) {
return successCode, updatePeriod
}
-// 获取节点告警信息
+//GetGatewayAlertInfo 获取节点告警信息
func GetGatewayAlertInfo() (string, int) {
db := database.GetConnection()
var apiAlertInfo string
diff --git a/server/dao/node-mysql/dao-plugin/plugin.go b/server/dao/node-mysql/dao-plugin/plugin.go
index 07072b6..ea324ac 100644
--- a/server/dao/node-mysql/dao-plugin/plugin.go
+++ b/server/dao/node-mysql/dao-plugin/plugin.go
@@ -1,10 +1,11 @@
-package dao_plugin
+package daoplugin
import (
"github.com/eolinker/goku-api-gateway/common/database"
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
+//GetAll 获取所有插件
func GetAll() (map[string]*entity.PluginInfo, error) {
const sql = "SELECT P.`pluginName`,P.`pluginPriority`,IFNULL(P.`pluginConfig`,''),P.`isStop`,P.`pluginType` FROM `goku_plugin` P WHERE P.`isCheck` = TRUE AND P.`pluginStatus` = 1;"
diff --git a/server/dao/node-mysql/dao-service/service.go b/server/dao/node-mysql/dao-service/service.go
index 459521d..67e4e7b 100644
--- a/server/dao/node-mysql/dao-service/service.go
+++ b/server/dao/node-mysql/dao-service/service.go
@@ -1,4 +1,4 @@
-package dao_service
+package daoservice
import (
"github.com/eolinker/goku-api-gateway/common/database"
@@ -7,6 +7,7 @@ import (
const sqlList = "SELECT `name`,`driver`,`default`,`desc`,`config`,`clusterConfig`,`healthCheck`,`healthCheckPath`,`healthCheckPeriod`,`healthCheckCode`,`healthCheckTimeOut` FROM `goku_service_config`"
+//GetAll 获取所有服务发现配置
func GetAll() ([]*entity.Service, error) {
stmt, e := database.GetConnection().Prepare(sqlList)
@@ -37,7 +38,6 @@ func GetAll() ([]*entity.Service, error) {
&v.HealthCheckPeriod,
&v.HealthCheckCode,
&v.HealthCheckTimeOut,
-
)
if er != nil {
return nil, er
diff --git a/server/dao/node-mysql/dao-strategy/strategy-api-plugin.go b/server/dao/node-mysql/dao-strategy/strategy-api-plugin.go
index 46ac9a9..7aadb13 100644
--- a/server/dao/node-mysql/dao-strategy/strategy-api-plugin.go
+++ b/server/dao/node-mysql/dao-strategy/strategy-api-plugin.go
@@ -1,12 +1,12 @@
-package dao_strategy
+package daostrategy
import (
"github.com/eolinker/goku-api-gateway/common/database"
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
-func GetApiPlugin() ([]*entity.StrategyApiPlugin, error) {
- //const sql="SELECT A.`apiID`,A.`strategyID`,A.`pluginName`,A.`pluginConfig` FROM `goku_conn_plugin_api` A INNER JOIN `goku_conn_strategy_api` SA ON A.`strategyID` = SA.`strategyID` AND A.`apiID` = SA.`apiID` INNER JOIN `goku_gateway_strategy` S ON S.`enableStatus` =1 AND A.`strategyID` = S.`strategyID` INNER JOIN `goku_gateway_api` API ON API.`apiID` = A.`apiID` INNER JOIN `goku_plugin` P ON P.`isCheck` = TRUE AND P.`pluginStatus` = 1 AND A.`pluginName` = P.`pluginName` ;"
+//GetAPIPlugin 获取接口插件列表
+func GetAPIPlugin() ([]*entity.StrategyAPIPlugin, error) {
const sql = "SELECT A.`apiID`,A.`strategyID`,A.`pluginName`,A.`pluginConfig`,IFNULL(A.`updateTag`,'') FROM `goku_conn_plugin_api` A INNER JOIN `goku_conn_strategy_api` SA ON A.`strategyID` = SA.`strategyID` AND A.`apiID` = SA.`apiID` INNER JOIN `goku_gateway_strategy` S ON A.`strategyID` = S.`strategyID` INNER JOIN `goku_gateway_api` API ON API.`apiID` = A.`apiID` INNER JOIN `goku_plugin` P ON P.`isCheck` = TRUE AND P.`pluginStatus` = 1 AND A.`pluginStatus` = 1 AND A.`pluginName` = P.`pluginName` ;"
stmt, e := database.GetConnection().Prepare(sql)
@@ -21,13 +21,13 @@ func GetApiPlugin() ([]*entity.StrategyApiPlugin, error) {
}
defer rows.Close()
- saps := make([]*entity.StrategyApiPlugin, 0, 200)
+ saps := make([]*entity.StrategyAPIPlugin, 0, 200)
for rows.Next() {
- sap := new(entity.StrategyApiPlugin)
+ sap := new(entity.StrategyAPIPlugin)
err := rows.Scan(
- &sap.ApiId,
+ &sap.APIId,
&sap.StrategyID,
&sap.PluginName,
&sap.PluginConfig,
diff --git a/server/dao/node-mysql/dao-strategy/strategy-api.go b/server/dao/node-mysql/dao-strategy/strategy-api.go
index 4d23837..63ae89e 100644
--- a/server/dao/node-mysql/dao-strategy/strategy-api.go
+++ b/server/dao/node-mysql/dao-strategy/strategy-api.go
@@ -1,13 +1,13 @@
-package dao_strategy
+package daostrategy
import (
"github.com/eolinker/goku-api-gateway/common/database"
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
-func GetAllStrategyApi() ([]*entity.StrategyApi, error) {
+//GetAllStrategyAPI 获取所有策略接口列表
+func GetAllStrategyAPI() ([]*entity.StrategyAPI, error) {
- //const sql = "SELECT A.`strategyID`,A.`apiID`,A.`target` FROM `goku_conn_strategy_api` A JOIN `goku_gateway_strategy` B ON A.`strategyID` = B.`strategyID` AND B.`enableStatus` = 1;"
const sql = "SELECT A.`strategyID`,A.`apiID`,IFNULL(A.`target`,'') FROM `goku_conn_strategy_api` A JOIN `goku_gateway_strategy` B ON A.`strategyID` = B.`strategyID` ;"
stmt, e := database.GetConnection().Prepare(sql)
@@ -21,11 +21,11 @@ func GetAllStrategyApi() ([]*entity.StrategyApi, error) {
}
defer rows.Close()
- apis := make([]*entity.StrategyApi, 0, 1000)
+ apis := make([]*entity.StrategyAPI, 0, 1000)
for rows.Next() {
- api := new(entity.StrategyApi)
- err := rows.Scan(&api.StrategyID, &api.ApiId, &api.Target)
+ api := new(entity.StrategyAPI)
+ err := rows.Scan(&api.StrategyID, &api.APIID, &api.Target)
if err != nil {
continue
}
diff --git a/server/dao/node-mysql/dao-strategy/strategy-plugin.go b/server/dao/node-mysql/dao-strategy/strategy-plugin.go
index 858cfe3..93f05fa 100644
--- a/server/dao/node-mysql/dao-strategy/strategy-plugin.go
+++ b/server/dao/node-mysql/dao-strategy/strategy-plugin.go
@@ -1,14 +1,13 @@
-package dao_strategy
+package daostrategy
import (
"github.com/eolinker/goku-api-gateway/common/database"
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
-// 获取策略组插件列表
+// GetAllStrategyPluginList 获取策略组插件列表
func GetAllStrategyPluginList() ([]*entity.StrategyPluginItem, error) {
- //sql := "SELECT A.`strategyID`,A.`pluginName`,A.`pluginConfig` FROM `goku_conn_plugin_strategy` A INNER JOIN `goku_gateway_strategy` S ON S.`enableStatus` =1 AND A.`strategyID` = S.`strategyID` INNER JOIN `goku_plugin` P ON P.`isCheck` = TRUE AND P.`pluginStatus` = 1 AND A.`pluginName` = P.`pluginName` WHERE A.`pluginStatus` = 1;"
sql := "SELECT A.`strategyID`,A.`pluginName`,A.`pluginConfig`,IFNULL(A.`updateTag`,'') FROM `goku_conn_plugin_strategy` A INNER JOIN `goku_gateway_strategy` S ON A.`strategyID` = S.`strategyID` INNER JOIN `goku_plugin` P ON P.`isCheck` = TRUE AND P.`pluginStatus` = 1 AND A.`pluginName` = P.`pluginName` WHERE A.`pluginStatus` = 1;"
stmt, e := database.GetConnection().Prepare(sql)
diff --git a/server/dao/node-mysql/dao-strategy/strategy.go b/server/dao/node-mysql/dao-strategy/strategy.go
index 669ec18..4614d7a 100644
--- a/server/dao/node-mysql/dao-strategy/strategy.go
+++ b/server/dao/node-mysql/dao-strategy/strategy.go
@@ -1,4 +1,4 @@
-package dao_strategy
+package daostrategy
import (
log "github.com/eolinker/goku-api-gateway/goku-log"
@@ -7,6 +7,7 @@ import (
entity "github.com/eolinker/goku-api-gateway/server/entity/node-entity"
)
+//GetAllStrategy 获取所有策略列表
func GetAllStrategy() (map[string]*entity.Strategy, *entity.Strategy, error) {
//const sql = "SELECT `strategyID`,`strategyName`,`auth` ,`strategyType` FROM `goku_gateway_strategy` WHERE `enableStatus` = 1;"
const sql = "SELECT `strategyID`,`strategyName`,`auth`,`enableStatus` ,`strategyType` FROM `goku_gateway_strategy`;"
@@ -21,7 +22,7 @@ func GetAllStrategy() (map[string]*entity.Strategy, *entity.Strategy, error) {
return nil, nil, e
}
defer rows.Close()
- var def *entity.Strategy = nil
+ var def *entity.Strategy
strategys := make(map[string]*entity.Strategy)
for rows.Next() {
s := new(entity.Strategy)
diff --git a/server/dao/update.go b/server/dao/update.go
index a7c9c6b..30b4ea3 100644
--- a/server/dao/update.go
+++ b/server/dao/update.go
@@ -8,7 +8,8 @@ import (
"github.com/eolinker/goku-api-gateway/common/database"
)
-func GetLastUpdateOfApi(tables ...string) (time.Time, error) {
+//GetLastUpdateOfAPI 获取最后更新的接口记录
+func GetLastUpdateOfAPI(tables ...string) (time.Time, error) {
t := time.Time{}
var updateTime string
tb := make([]string, len(tables))
@@ -30,6 +31,7 @@ func GetLastUpdateOfApi(tables ...string) (time.Time, error) {
return t, nil
}
+//UpdateTable 更新goku_table_update_record的updateTime字段
func UpdateTable(name string) error {
db := database.GetConnection()
now := time.Now().Format("2006-01-02 15:04:05")
diff --git a/server/entity/alert.go b/server/entity/alert.go
index 281a5d2..dcf9434 100644
--- a/server/entity/alert.go
+++ b/server/entity/alert.go
@@ -1,5 +1,6 @@
package entity
+//AlertInfo 告警信息
type AlertInfo struct {
ReceiverList string `json:"receiverList"`
AlertAddr string `json:"alertAddr"`
diff --git a/server/entity/balance-entity-service/balance.go b/server/entity/balance-entity-service/balance.go
index 2ddc22f..21953fe 100644
--- a/server/entity/balance-entity-service/balance.go
+++ b/server/entity/balance-entity-service/balance.go
@@ -2,6 +2,7 @@ package entity
import "github.com/eolinker/goku-api-gateway/server/driver"
+//Balance 负载
type Balance struct {
Name string
ServiceName string
@@ -15,6 +16,7 @@ type Balance struct {
UpdateTime string
}
+//Type 获取负载类型
func (e *Balance) Type() *Balance {
if e != nil {
diff --git a/server/entity/balance-entity/balance.go b/server/entity/balance-entity/balance.go
index f71c501..5a66bc1 100644
--- a/server/entity/balance-entity/balance.go
+++ b/server/entity/balance-entity/balance.go
@@ -9,6 +9,7 @@ import (
jsoniter "github.com/json-iterator/go"
)
+//BalanceInfoEntity 负载信息结构体
type BalanceInfoEntity struct {
Name string
Desc string
@@ -20,6 +21,8 @@ type BalanceInfoEntity struct {
CreateTime string
UpdateTime string
}
+
+//BalanceInfo 负载信息
type BalanceInfo struct {
Name string `json:"balanceName"`
Desc string `json:"balanceDesc"`
@@ -29,14 +32,17 @@ type BalanceInfo struct {
CreateTime string `json:"createTime"`
UpdateTime string `json:"updateTime"`
}
+
+//BalanceConfig 负载配置
type BalanceConfig struct {
- DiscoveryId int64 `json:"serviceDiscoveryID"`
+ DiscoveryID int64 `json:"serviceDiscoveryID"`
ServiceName string `json:"serviceName"`
Servers []*BalanceServerConfig `json:"-"`
ServersConfig []string `json:"static"`
ServersConfigOrg string `json:"staticOrg"`
}
+//BalanceServerConfig 负载服务器配置
type BalanceServerConfig struct {
Server string `json:"server"`
Weight int `json:"weight"`
@@ -60,6 +66,7 @@ type _OldVersionBalanceInfo struct {
//
//}
+//Decode 解码
func (ent *BalanceInfoEntity) Decode() (*BalanceInfo, error) {
info := new(BalanceInfo)
info.Name = ent.Name
@@ -81,7 +88,7 @@ func (ent *BalanceInfoEntity) Decode() (*BalanceInfo, error) {
}
info.Default = &BalanceConfig{
- DiscoveryId: 0,
+ DiscoveryID: 0,
ServiceName: "",
Servers: config,
ServersConfig: FormatServers(config),
@@ -102,6 +109,7 @@ func (ent *BalanceInfoEntity) Decode() (*BalanceInfo, error) {
}
+//TryOld try old config
func TryOld(oldversionConfig string) ([]*BalanceServerConfig, error) {
if oldversionConfig == "" {
return nil, nil
@@ -121,6 +129,7 @@ func TryOld(oldversionConfig string) ([]*BalanceServerConfig, error) {
//return Default, err
}
+//GetConfig 获取配置
func (info *BalanceInfo) GetConfig(clusterName string) *BalanceConfig {
c, has := info.Cluster[clusterName]
if !has || len(c.Servers) < 1 {
@@ -129,6 +138,8 @@ func (info *BalanceInfo) GetConfig(clusterName string) *BalanceConfig {
// todo: 服务发现需要另外处理,暂时不接入
return c
}
+
+//FormatServers 格式化
func FormatServers(servers []*BalanceServerConfig) []string {
if len(servers) == 0 {
return nil
@@ -163,13 +174,15 @@ func fields(str string) []string {
})
return words
}
+
+//Decode 解析配置
func (c *BalanceConfig) Decode() error {
words := fields(c.ServersConfigOrg)
s := make([]*BalanceServerConfig, 0, 5)
- var node *BalanceServerConfig = nil
+ var node *BalanceServerConfig
index := 0
for _, word := range words {
if word == ";" {
diff --git a/server/entity/cluster.go b/server/entity/cluster.go
index 7a3444f..e8d70f9 100644
--- a/server/entity/cluster.go
+++ b/server/entity/cluster.go
@@ -3,19 +3,25 @@ package entity
import "fmt"
//const ClusterDefaultName = "default"
+
+//Cluster cluster
type Cluster struct {
- Id int `json:"-" yaml:"-"`
+ ID int `json:"-" yaml:"-"`
Name string `json:"name" yaml:"name"`
Title string `json:"title" yaml:"title"`
}
+
+//ClusterInfo 集群信息
type ClusterInfo struct {
- Id int `json:"-" yaml:"-"`
+ ID int `json:"-" yaml:"-"`
Name string `json:"name" yaml:"name"`
Title string `json:"title" yaml:"title"`
Note string `json:"note" yaml:"note"`
DB ClusterDB `json:"db" yaml:"db"`
Redis CLusterRedis `json:"redis" yaml:"redis"`
}
+
+//ClusterDB cluster db
type ClusterDB struct {
Driver string `json:"driver" yaml:"driver"`
Host string `json:"host" yaml:"host"`
@@ -24,6 +30,8 @@ type ClusterDB struct {
Password string `json:"password" yaml:"password"`
Database string `json:"database" yaml:"database"`
}
+
+//CLusterRedis cluster redis
type CLusterRedis struct {
Mode string `json:"mode" yaml:"mode"`
Addrs string `json:"addrs" yaml:"addrs"`
@@ -32,17 +40,20 @@ type CLusterRedis struct {
Password string `json:"password" yaml:"password"`
}
+//GetDriver 获取驱动
func (c *ClusterDB) GetDriver() string {
return c.Driver
}
+//GetSource 获取源字符串
func (c *ClusterDB) GetSource() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", c.UserName, c.Password, c.Host, c.Port, c.Database)
}
+//Cluster 获取cluster
func (c *ClusterInfo) Cluster() *Cluster {
return &Cluster{
- Id: c.Id,
+ ID: c.ID,
Name: c.Name,
Title: c.Title,
}
diff --git a/server/entity/config-log/log.go b/server/entity/config-log/log.go
index 44e4f2b..de3c8eb 100644
--- a/server/entity/config-log/log.go
+++ b/server/entity/config-log/log.go
@@ -1,5 +1,6 @@
package entity
+//LogConfig 日志配置
type LogConfig struct {
Name string
Enable int
diff --git a/server/entity/console-entity/ams_import.go b/server/entity/console-entity/ams_import.go
index ac2ef60..f4c9812 100644
--- a/server/entity/console-entity/ams_import.go
+++ b/server/entity/console-entity/ams_import.go
@@ -1,27 +1,32 @@
package entity
+//AmsProject ams项目
type AmsProject struct {
ProjectInfo AmsProjectInfo `json:"projectInfo"`
- ApiGroupList []AmsGroupInfo `json:"apiGroupList"`
+ APIGroupList []AmsGroupInfo `json:"apiGroupList"`
}
+//AmsProjectInfo ams项目信息
type AmsProjectInfo struct {
ProjectName string `json:"projectName"`
}
+//AmsGroupInfo ams分组信息
type AmsGroupInfo struct {
GroupName string `json:"groupName"`
ChildGroupList []AmsGroupInfo `json:"childGroupList"`
- ApiList []AmsApiInfo `json:"apiList"`
- ApiGroupChildList []AmsGroupInfo `json:"apiGroupChildList"`
+ APIList []AmsAPIInfo `json:"apiList"`
+ APIGroupChildList []AmsGroupInfo `json:"apiGroupChildList"`
}
-type AmsApiInfo struct {
- BaseInfo AmsApi `json:"baseInfo"`
+//AmsAPIInfo ams接口信息
+type AmsAPIInfo struct {
+ BaseInfo AmsAPI `json:"baseInfo"`
}
-type AmsApi struct {
- ApiName string `json:"apiName"`
- ApiURI string `json:"apiURI"`
- ApiRequestType int `json:"apiRequestType"`
+//AmsAPI ams接口
+type AmsAPI struct {
+ APIName string `json:"apiName"`
+ APIURI string `json:"apiURI"`
+ APIRequestType int `json:"apiRequestType"`
}
diff --git a/server/entity/console-entity/api.go b/server/entity/console-entity/api.go
index 0f37047..8449285 100644
--- a/server/entity/console-entity/api.go
+++ b/server/entity/console-entity/api.go
@@ -1,8 +1,9 @@
package entity
-type Api struct {
- ApiID int `json:"apiID"`
- ApiName string `json:"apiName"`
+//API 接口
+type API struct {
+ APIID int `json:"apiID"`
+ APIName string `json:"apiName"`
GroupID int `json:"groupID,omitempty"`
ProjectID int `json:"projectID,omitempty"`
RequestURL string `json:"requestURL"`
@@ -26,6 +27,7 @@ type Api struct {
*ManagerInfo
}
+//ManagerInfo 管理者信息
type ManagerInfo struct {
ManagerID int `json:"managerID"`
UpdaterID int `json:"updaterID"`
@@ -35,14 +37,16 @@ type ManagerInfo struct {
CreateUserName string `json:"createUserName"`
}
+//RequestParam 请求参数
type RequestParam struct {
Key string `json:"key"`
KeyPosition string `json:"keyPosition"`
NotEmpty bool `json:"notEmpty"`
}
-type ApiPlugin struct {
- *Api
+//APIPlugin 接口插件
+type APIPlugin struct {
+ *API
StrategyID string
PluginList []*PluginParams
StrategyPluginList []*PluginParams
diff --git a/server/entity/console-entity/message.go b/server/entity/console-entity/message.go
index abe66e1..c1b1634 100644
--- a/server/entity/console-entity/message.go
+++ b/server/entity/console-entity/message.go
@@ -1,5 +1,6 @@
package entity
+//Message 消息
type Message struct {
MsgID int `json:"msgID"`
Msg string `json:"msg"`
diff --git a/server/entity/console-entity/node.go b/server/entity/console-entity/node.go
index d2cbe0f..c9f7e1f 100644
--- a/server/entity/console-entity/node.go
+++ b/server/entity/console-entity/node.go
@@ -1,5 +1,6 @@
package entity
+//Node 节点
type Node struct {
NodeID int `json:"nodeID"`
NodeName string `json:"nodeName"`
diff --git a/server/entity/console-entity/plugin.go b/server/entity/console-entity/plugin.go
index eeefe74..28347a5 100644
--- a/server/entity/console-entity/plugin.go
+++ b/server/entity/console-entity/plugin.go
@@ -1,8 +1,9 @@
package entity
-var GlobalPlugin map[string]*Plugin = make(map[string]*Plugin)
+//GlobalPlugin 全局插件
+var GlobalPlugin = make(map[string]*Plugin)
-// 插件
+// Plugin 插件
type Plugin struct {
PluginID int `json:"pluginID"`
PluginName string `json:"pluginName"`
@@ -19,10 +20,12 @@ type Plugin struct {
IsCheck int `json:"isCheck"`
}
+//PluginList 插件列表
type PluginList struct {
PluginList []*PluginParams `json:"pluginList"`
}
+//PluginParams 插件参数
type PluginParams struct {
PluginName string `json:"pluginName"`
PluginConfig string `json:"pluginConfig"`
@@ -30,6 +33,7 @@ type PluginParams struct {
PluginInfo map[string]string `json:"pluginInfo"`
}
+//PluginSlice 插件切片
type PluginSlice []*Plugin
func (p PluginSlice) Len() int { // 重写 Len() 方法
@@ -42,6 +46,7 @@ func (p PluginSlice) Less(i, j int) bool { // 重写 Less() 方法, 从小到
return p[i].PluginIndex < p[j].PluginIndex
}
+//ProxyCachingConf 转发缓存配置
type ProxyCachingConf struct {
ResponseCodes string `json:"responseCodes"` //缓存条件:返回的HTTP状态码在该状态码列表中
RequestMethods string `json:"requestMethods"` //缓存条件:请求的Method在该列表中
diff --git a/server/entity/console-entity/project.go b/server/entity/console-entity/project.go
index 75fed4f..3685cb4 100644
--- a/server/entity/console-entity/project.go
+++ b/server/entity/console-entity/project.go
@@ -1,5 +1,6 @@
package entity
+//Project 项目
type Project struct {
ProjectID int `json:"projectID"`
ProjectName string `json:"projectName"`
diff --git a/server/entity/console-entity/redis.go b/server/entity/console-entity/redis.go
index da1d559..aa2fd6d 100644
--- a/server/entity/console-entity/redis.go
+++ b/server/entity/console-entity/redis.go
@@ -1,7 +1,8 @@
package entity
+//RedisNode redis节点信息
type RedisNode struct {
Server string
Password string
- ClusterId int
+ ClusterID int
}
diff --git a/server/entity/console-entity/service.go b/server/entity/console-entity/service.go
index a6cf4a3..409f402 100644
--- a/server/entity/console-entity/service.go
+++ b/server/entity/console-entity/service.go
@@ -1,5 +1,6 @@
package entity
+//Service service
type Service struct {
Name string
Driver string
diff --git a/server/entity/console-entity/sql.go b/server/entity/console-entity/sql.go
index 9fa6766..d8c6fe5 100644
--- a/server/entity/console-entity/sql.go
+++ b/server/entity/console-entity/sql.go
@@ -1,14 +1,17 @@
package entity
+//Table table
type Table struct {
TableName string `json:"tableName"`
TableColumn []string `json:"tableColumn"`
}
+//TableData tableData
type TableData struct {
Data []map[string]interface{}
}
+//ColumnInfo column info
type ColumnInfo struct {
FieldName string
Type interface{}
@@ -18,6 +21,7 @@ type ColumnInfo struct {
Extra interface{}
}
+//GokuAdmin 网关超级管理员信息
type GokuAdmin struct {
UserID int `json:"userID"`
LoginCall string `json:"loginCall"`
@@ -25,6 +29,7 @@ type GokuAdmin struct {
UserType int `json:"userType"`
}
+//GokuBalance 网关负载
type GokuBalance struct {
BalanceID int `json:"balanceID"`
BalanceName string `json:"balanceName"`
@@ -33,11 +38,13 @@ type GokuBalance struct {
UpdateTime string `json:"updateTime"`
}
-type GokuConnPluginApi struct {
+//GokuConnPluginAPI goku conn plgin api
+type GokuConnPluginAPI struct {
ConnID int `json:"connID"`
- ApiID int `json:"apiID"`
+ APIID int `json:"apiID"`
}
+//ColumnValue column value
type ColumnValue struct {
Value interface{}
}
diff --git a/server/entity/console-entity/strategy.go b/server/entity/console-entity/strategy.go
index 312064d..7e2ee8e 100644
--- a/server/entity/console-entity/strategy.go
+++ b/server/entity/console-entity/strategy.go
@@ -1,5 +1,6 @@
package entity
+//Strategy 策略
type Strategy struct {
StrategyID string `json:"strategyID"`
StrategyName string `json:"strategyName"`
diff --git a/server/entity/console-entity/user.go b/server/entity/console-entity/user.go
index 4b26023..66cf5b9 100644
--- a/server/entity/console-entity/user.go
+++ b/server/entity/console-entity/user.go
@@ -1,5 +1,6 @@
package entity
+//UserInfo 用户信息
type UserInfo struct {
UserID int `json:"userID"`
LoginCall string `json:"loginCall"`
diff --git a/server/entity/node-entity/api.go b/server/entity/node-entity/api.go
index 1c13a06..384b131 100644
--- a/server/entity/node-entity/api.go
+++ b/server/entity/node-entity/api.go
@@ -1,8 +1,9 @@
package entity
-type Api struct {
- ApiID int
- ApiName string
+//API api
+type API struct {
+ APIID int
+ APIName string
RequestURL string
RequestMethod string
Protocol string
@@ -17,7 +18,8 @@ type Api struct {
StripSlash bool // 是否过滤斜杠
}
-type ApiExtend struct {
- *Api
+//APIExtend api extend
+type APIExtend struct {
+ *API
Target string
}
diff --git a/server/entity/node-entity/balance.go b/server/entity/node-entity/balance.go
index bb60f7e..a3f3cf2 100644
--- a/server/entity/node-entity/balance.go
+++ b/server/entity/node-entity/balance.go
@@ -2,6 +2,7 @@ package entity
import "github.com/eolinker/goku-api-gateway/server/driver"
+//Balance balance
type Balance struct {
Name string
ServiceName string
@@ -12,6 +13,7 @@ type Balance struct {
StaticCluster string
}
+//Type type
func (e *Balance) Type() *Balance {
if e != nil {
diff --git a/server/entity/node-entity/monitor.go b/server/entity/node-entity/monitor.go
index 73f9ece..4817b48 100644
--- a/server/entity/node-entity/monitor.go
+++ b/server/entity/node-entity/monitor.go
@@ -1,8 +1,9 @@
package entity
+//MonitorConfig 监控配置
type MonitorConfig struct {
- ApiMonitorStatus int
+ APIMonitorStatus int
StrategyMonitorStatus int
- StrategyMonitorStatusInApi int
- ApiMonitorStatusInStrategy int
+ StrategyMonitorStatusInAPI int
+ APIMonitorStatusInStrategy int
}
diff --git a/server/entity/node-entity/plugin.go b/server/entity/node-entity/plugin.go
index cf266a5..1818a44 100644
--- a/server/entity/node-entity/plugin.go
+++ b/server/entity/node-entity/plugin.go
@@ -5,11 +5,15 @@ import (
)
const (
- PluginTypeGateway = 0
+ //PluginTypeGateway 全局插件
+ PluginTypeGateway = 0
+ //PluginTypeStrategy 策略插件
PluginTypeStrategy = 1
- PluginTypeApi = 2
+ //PluginTypeAPI 接口插件
+ PluginTypeAPI = 2
)
+//PluginInfo 插件信息
type PluginInfo struct {
Name string
Priority int
@@ -18,8 +22,11 @@ type PluginInfo struct {
Type int
UpdateTag string
}
+
+//MapString map string
type MapString map[string]string
+//PluginFactoryHandler 插件处理factory
type PluginFactoryHandler struct {
Info *PluginInfo
Factory goku_plugin.PluginFactory
@@ -28,6 +35,7 @@ type PluginFactoryHandler struct {
//UpdateTag string
}
+//PluginHandlerExce plugin handler exec
type PluginHandlerExce struct {
PluginObj *goku_plugin.PluginObj
Name string
@@ -35,6 +43,7 @@ type PluginHandlerExce struct {
IsStop bool
}
+//PluginSlice 插件切片
type PluginSlice []*PluginHandlerExce
func (p PluginSlice) Len() int { // 重写 Len() 方法
diff --git a/server/entity/node-entity/service.go b/server/entity/node-entity/service.go
index 274bd9e..5f7b63d 100644
--- a/server/entity/node-entity/service.go
+++ b/server/entity/node-entity/service.go
@@ -1,5 +1,6 @@
package entity
+//Service service
type Service struct {
Name string
Driver string
diff --git a/server/entity/node-entity/strategy.go b/server/entity/node-entity/strategy.go
index ea4dde8..e7feb33 100644
--- a/server/entity/node-entity/strategy.go
+++ b/server/entity/node-entity/strategy.go
@@ -1,5 +1,6 @@
package entity
+//Strategy strategy
type Strategy struct {
StrategyID string
StrategyName string
@@ -13,6 +14,7 @@ type Strategy struct {
// return s.EnableStatus ==1
//}
+//StrategyPluginItem strategy plugin item
type StrategyPluginItem struct {
StrategyID string
PluginName string
@@ -21,15 +23,19 @@ type StrategyPluginItem struct {
//PluginInfo string
//PluginStatus int
}
-type StrategyApiPlugin struct {
- ApiId string
+
+//StrategyAPIPlugin 策略接口插件
+type StrategyAPIPlugin struct {
+ APIId string
StrategyID string
PluginName string
PluginConfig string
UpdateTag string
}
-type StrategyApi struct {
- ApiId int
+
+//StrategyAPI 策略接口
+type StrategyAPI struct {
+ APIID int
StrategyID string
Target string
}
diff --git a/server/entity/plugin-entity/plugin.go b/server/entity/plugin-entity/plugin.go
index 250ac12..3eda0f6 100644
--- a/server/entity/plugin-entity/plugin.go
+++ b/server/entity/plugin-entity/plugin.go
@@ -1,8 +1,9 @@
-package plugin_entity
+package pluginentity
-var GlobalPlugin map[string]*Plugin = make(map[string]*Plugin)
+//GlobalPlugin 全局插件
+var GlobalPlugin = make(map[string]*Plugin)
-// 插件
+//Plugin 插件
type Plugin struct {
PluginID int `json:"pluginID"`
PluginName string `json:"pluginName"`
@@ -13,6 +14,7 @@ type Plugin struct {
IsStop int `json:"isStop"`
}
+//PluginParams pluginParams
type PluginParams struct {
PluginName string `json:"pluginName"`
PluginConfig string `json:"pluginConfig"`
@@ -21,6 +23,7 @@ type PluginParams struct {
IsStop int `json:"isStop"`
}
+//PluginSlice 插件切片
type PluginSlice []*Plugin
func (p PluginSlice) Len() int { // 重写 Len() 方法
diff --git a/server/entity/redis_config.go b/server/entity/redis_config.go
index efcc06d..2ba7043 100644
--- a/server/entity/redis_config.go
+++ b/server/entity/redis_config.go
@@ -4,22 +4,27 @@ import (
"strings"
)
+//GetMode 获取redis模式
func (c CLusterRedis) GetMode() string {
return c.Mode
}
+//GetAddrs 获取地址
func (c CLusterRedis) GetAddrs() []string {
return strings.Split(c.Addrs, ",")
}
+//GetMasters getMasters
func (c CLusterRedis) GetMasters() []string {
return strings.Split(c.Masters, ",")
}
+//GetDbIndex 获取数据序号
func (c CLusterRedis) GetDbIndex() int {
return c.DbIndex
}
+//GetPassword 获取密码
func (c CLusterRedis) GetPassword() string {
return c.Password
}
diff --git a/server/entity/result_info.go b/server/entity/result_info.go
index 7e4732b..8d50f90 100644
--- a/server/entity/result_info.go
+++ b/server/entity/result_info.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
)
+//ResultInfo 结果信息
type ResultInfo struct {
ResultType string `json:"type"`
StatusCode string `json:"statusCode"`
@@ -12,6 +13,7 @@ type ResultInfo struct {
ResultDesc string `json:"resultDesc,omitempty"`
}
+//String string
func String(info interface{}) string {
resultInfo, err := json.Marshal(info)
if err != nil {
@@ -20,6 +22,7 @@ func String(info interface{}) string {
return string(resultInfo)
}
+//GetResultInfo 获取结果信息
func GetResultInfo(statusCode string, resultType string, resultKey string, resultDesc string, result interface{}, successCount string) map[string]interface{} {
if resultKey == "" {
return map[string]interface{}{
@@ -27,20 +30,18 @@ func GetResultInfo(statusCode string, resultType string, resultKey string, resul
"statusCode": statusCode,
"resultDesc": resultDesc,
}
- } else {
- if result != nil {
- return map[string]interface{}{
- "type": resultType,
- "statusCode": statusCode,
- resultKey: result,
- "resultDesc": resultDesc,
- }
- } else {
- return map[string]interface{}{
- "type": resultType,
- "statusCode": statusCode,
- "resultDesc": resultDesc,
- }
+ }
+ if result != nil {
+ return map[string]interface{}{
+ "type": resultType,
+ "statusCode": statusCode,
+ resultKey: result,
+ "resultDesc": resultDesc,
}
}
+ return map[string]interface{}{
+ "type": resultType,
+ "statusCode": statusCode,
+ "resultDesc": resultDesc,
+ }
}
diff --git a/server/monitor/monitor-key/key.go b/server/monitor/monitor-key/key.go
index 9a90980..dcc6359 100644
--- a/server/monitor/monitor-key/key.go
+++ b/server/monitor/monitor-key/key.go
@@ -1,8 +1,10 @@
-package monitor_key
+package monitorkey
+//MonitorKeyType 监控Key类型
type MonitorKeyType int
const (
+ // GatewayRequestCount 请求次数信息
GatewayRequestCount MonitorKeyType = iota
GatewaySuccessCount
GatewayStatus2xxCount
@@ -30,10 +32,13 @@ func init() {
}
keys = ks
}
+
+//Keys
func Keys() []MonitorKeyType {
return keys
}
+//ToString toString
func ToString(key int) string {
return MonitorKeyType(key).String()
}
diff --git a/server/monitor/monitor-key/redis.go b/server/monitor/monitor-key/redis.go
index 54dc955..d7b6ea9 100644
--- a/server/monitor/monitor-key/redis.go
+++ b/server/monitor/monitor-key/redis.go
@@ -1,22 +1,27 @@
-package monitor_key
+package monitorkey
import (
"bytes"
)
+//StrategyMapKey 策略字典Key
func StrategyMapKey(cluster, now string) string {
key := splicing("monitor-strategy:", cluster, ":", now)
//fmt.Println("StrategyMapKey:",key)
return key
}
-func APiMapKey(cluster, strategyId, now string) string {
- key := splicing("monitor-api:", cluster, ":", strategyId, ":", now)
- //fmt.Println("APiMapKey:",key)
+
+//APIMapKey 接口字典key
+func APIMapKey(cluster, strategyID, now string) string {
+ key := splicing("monitor-api:", cluster, ":", strategyID, ":", now)
+ //fmt.Println("APIMapKey:",key)
return key
}
-func ApiValueKey(cluster, strategyId string, apiId string, now string) string {
- key := splicing("monitor-value:", cluster, ":", strategyId, ":", apiId, ":", now)
- //fmt.Println("ApiValueKey:",key)
+
+//APIValueKey api value key
+func APIValueKey(cluster, strategyID string, apiID string, now string) string {
+ key := splicing("monitor-value:", cluster, ":", strategyID, ":", apiID, ":", now)
+ //fmt.Println("APIValueKey:",key)
return key
}
diff --git a/server/monitor/monitor-key/value.go b/server/monitor/monitor-key/value.go
index 98e4dd4..ddc460c 100644
--- a/server/monitor/monitor-key/value.go
+++ b/server/monitor/monitor-key/value.go
@@ -1,13 +1,17 @@
-package monitor_key
+package monitorkey
+//MonitorValues monitorValues
type MonitorValues []int64
+//Add add
func (a MonitorValues) Add(key MonitorKeyType) {
index := int(key)
if index < len(a) {
a[index]++
}
}
+
+//Get get
func (a MonitorValues) Get(key MonitorKeyType) int64 {
if a == nil {
return 0
@@ -18,6 +22,8 @@ func (a MonitorValues) Get(key MonitorKeyType) int64 {
}
return 0
}
+
+//Append append
func (a MonitorValues) Append(args ...MonitorValues) {
if len(args) == 0 {
return
@@ -32,6 +38,7 @@ func (a MonitorValues) Append(args ...MonitorValues) {
return
}
+//MakeValue make value
func MakeValue() MonitorValues {
return make(MonitorValues, MonitorKeyTypeSize)
}
diff --git a/server/monitor/monitor-read/monitor.go b/server/monitor/monitor-read/monitor.go
index ed794f9..7f21f84 100644
--- a/server/monitor/monitor-read/monitor.go
+++ b/server/monitor/monitor-read/monitor.go
@@ -1,4 +1,4 @@
-package monitor_read
+package monitorread
import (
"fmt"
@@ -14,9 +14,12 @@ var (
period = 30 * time.Second
)
+//SetPeriod 设置更新周期
func SetPeriod(sec int) {
period = time.Duration(sec) * time.Second
}
+
+//InitMonitorRead init monitor read
func InitMonitorRead(clusters []*entity.Cluster) error {
for _, c := range clusters {
_, has := redis_manager.Get(c.Name)
@@ -25,12 +28,12 @@ func InitMonitorRead(clusters []*entity.Cluster) error {
}
}
for _, c := range clusters {
- go doLoopForCluster(c.Name, c.Id)
+ go doLoopForCluster(c.Name, c.ID)
}
return nil
}
-func doLoopForCluster(clusterName string, clusterId int) {
+func doLoopForCluster(clusterName string, clusterID int) {
t := time.NewTimer(period)
@@ -38,58 +41,57 @@ func doLoopForCluster(clusterName string, clusterId int) {
select {
case <-t.C:
{
- read(clusterName, clusterId, time.Now())
+ read(clusterName, clusterID, time.Now())
}
}
t.Reset(period)
}
}
-func read(clusterName string, clusterId int, t time.Time) {
+func read(clusterName string, clusterID int, t time.Time) {
hour := t.Format("2006010215")
now := t.Format("2006-01-02 15:04:05")
hourValue, _ := strconv.Atoi(hour)
// 包含 strate == ""
- strategyIds, err := readStrategyId(hour, clusterName)
+ strategyIds, err := readStrategyID(hour, clusterName)
if err != nil {
return
}
- for _, strategyId := range strategyIds {
+ for _, strategyID := range strategyIds {
- apiIds, err := readApiId(hour, clusterName, strategyId)
+ apiIds, err := readAPIId(hour, clusterName, strategyID)
if err != nil {
continue
}
- for _, apiId := range apiIds {
+ for _, apiID := range apiIds {
- valus, err := readValue(hour, clusterName, strategyId, apiId)
+ valus, err := readValue(hour, clusterName, strategyID, apiID)
if err != nil {
continue
}
- apiID, _ := strconv.Atoi(apiId)
+ apiID, _ := strconv.Atoi(apiID)
- dao_monitor.Save(strategyId, apiID, clusterId, hourValue, now, valus)
+ dao_monitor.Save(strategyID, apiID, clusterID, hourValue, now, valus)
}
}
}
-func readStrategyId(now, cluster string) ([]string, error) {
- key := monitor_key.StrategyMapKey(cluster, now)
+func readStrategyID(now, cluster string) ([]string, error) {
+ key := monitorkey.StrategyMapKey(cluster, now)
conn, _ := redis_manager.Get(cluster)
return conn.HKeys(key).Result()
}
-func readApiId(now, cluster, strategyId string) ([]string, error) {
- key := monitor_key.APiMapKey(cluster, strategyId, now)
+func readAPIId(now, cluster, strategyID string) ([]string, error) {
+ key := monitorkey.APIMapKey(cluster, strategyID, now)
conn, _ := redis_manager.Get(cluster)
return conn.HKeys(key).Result()
}
-func readValue(now, cluster, strategyId string, apiId string) (map[string]string, error) {
+func readValue(now, cluster, strategyID string, apiID string) (map[string]string, error) {
conn, _ := redis_manager.Get(cluster)
- key := monitor_key.ApiValueKey(cluster, strategyId, apiId, now)
+ key := monitorkey.APIValueKey(cluster, strategyID, apiID, now)
return conn.HGetAll(key).Result()
-
}
diff --git a/server/monitor/monitor-write/monitor.go b/server/monitor/monitor-write/monitor.go
index c4f167f..9359d26 100644
--- a/server/monitor/monitor-write/monitor.go
+++ b/server/monitor/monitor-write/monitor.go
@@ -1,9 +1,9 @@
-package monitor_write
+package monitorwrite
import (
"time"
- "github.com/eolinker/goku-api-gateway/common/redis-manager"
+ redis_manager "github.com/eolinker/goku-api-gateway/common/redis-manager"
gateway_manager "github.com/eolinker/goku-api-gateway/goku-node/manager/gateway-manager"
monitor_key "github.com/eolinker/goku-api-gateway/server/monitor/monitor-key"
)
@@ -17,8 +17,8 @@ var (
)
type _Action struct {
- StrategyId string
- ApiId string
+ StrategyID string
+ APIID string
Keys []monitor_key.MonitorKeyType
}
type _MonitorMap struct {
@@ -29,6 +29,7 @@ type _StrategyInfo struct {
values map[string]monitor_key.MonitorValues
}
+//InitMonitorWrite 初始化监控写入器
func InitMonitorWrite(clusterName string) {
cluster = clusterName
go saveLoop()
@@ -48,16 +49,16 @@ func saveLoop() {
tnow := m.now.Format("2006010215")
strategyMapKey := monitor_key.StrategyMapKey(cluster, tnow)
- for strategyId, strategy := range m.strategys {
- pipeline.HSetNX(strategyMapKey, strategyId, 1)
+ for strategyID, strategy := range m.strategys {
+ pipeline.HSetNX(strategyMapKey, strategyID, 1)
- apisOfStrategyKey := monitor_key.APiMapKey(cluster, strategyId, tnow)
+ apisOfStrategyKey := monitor_key.APIMapKey(cluster, strategyID, tnow)
- for apiId, values := range strategy.values {
+ for apiID, values := range strategy.values {
- pipeline.HSetNX(apisOfStrategyKey, apiId, 1)
+ pipeline.HSetNX(apisOfStrategyKey, apiID, 1)
- key := monitor_key.ApiValueKey(cluster, strategyId, apiId, tnow)
+ key := monitor_key.APIValueKey(cluster, strategyID, apiID, tnow)
for k, v := range values {
if v > 0 {
pipeline.HIncrBy(key, monitor_key.ToString(k), v)
@@ -96,18 +97,18 @@ func temporaryStorage() {
return
}
- strategy, has := ts.strategys[action.StrategyId]
+ strategy, has := ts.strategys[action.StrategyID]
if !has {
strategy = &_StrategyInfo{
values: make(map[string]monitor_key.MonitorValues),
}
- ts.strategys[action.StrategyId] = strategy
+ ts.strategys[action.StrategyID] = strategy
}
- apivalue, has := strategy.values[action.ApiId]
+ apivalue, has := strategy.values[action.APIID]
if !has {
apivalue = monitor_key.MakeValue()
- strategy.values[action.ApiId] = apivalue
+ strategy.values[action.APIID] = apivalue
}
for _, i := range action.Keys {
@@ -117,13 +118,14 @@ func temporaryStorage() {
}
}
-func AddMonitor(strategyId string, apiId string, proxyStatusCode int, gatewayStatusCode int) {
+//AddMonitor 新增监控
+func AddMonitor(strategyID string, apiID string, proxyStatusCode int, gatewayStatusCode int) {
keys := createField(proxyStatusCode, gatewayStatusCode)
add(&_Action{
- StrategyId: strategyId,
- ApiId: apiId,
+ StrategyID: strategyID,
+ APIID: apiID,
Keys: keys,
})
// proxyStatusCode == 0 没有进行转发
diff --git a/utils/alert.go b/utils/alert.go
index 93c29e3..16ff2d9 100644
--- a/utils/alert.go
+++ b/utils/alert.go
@@ -20,6 +20,7 @@ func init() {
currentAlertBody = string(body)
}
+//SendAlertMail 发送告警邮件
func SendAlertMail(sender, senderPassword, smtpAddress, smtpPort, smtpProtocol, receiverMail, requestURL, alertLogPath, alertPeriod, alertCount, apiName, apiID, targetServer, proxyURL string) (bool, error) {
alertTime := time.Now().Format("2006-01-02 15:04:05")
diff --git a/utils/function.go b/utils/function.go
index 9094ef2..6429ffa 100644
--- a/utils/function.go
+++ b/utils/function.go
@@ -3,9 +3,7 @@ package utils
import (
"crypto/md5"
"encoding/hex"
- "fmt"
"math/rand"
- "net"
"os"
"os/exec"
"regexp"
@@ -14,17 +12,16 @@ import (
"time"
)
-// 将string转为int类型
+//ConvertString 将string转为int类型
func ConvertString(params string) (int, bool) {
id, err := strconv.Atoi(params)
if err != nil {
return 0, false
- } else {
- return id, true
}
+ return id, true
}
-// 判断ip端口是否合法
+//ValidateRemoteAddr 判断ip端口是否合法
func ValidateRemoteAddr(ip string) bool {
match, err := regexp.MatchString(`^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))\:(([0-9])|([1-9][0-9]{1,3})|([1-6][0-9]{0,4}))$`, ip)
if err != nil {
@@ -33,6 +30,7 @@ func ValidateRemoteAddr(ip string) bool {
return match
}
+//InterceptIP 过滤IP
func InterceptIP(str, substr string) string {
result := strings.Index(str, substr)
var rs string
@@ -44,13 +42,14 @@ func InterceptIP(str, substr string) string {
return rs
}
+//Md5 md5
func Md5(encodeString string) string {
h := md5.New()
h.Write([]byte(encodeString))
return hex.EncodeToString(h.Sum(nil)) // 输出加密结果
}
-//生成随机字符串
+//GetRandomString 生成随机字符串
func GetRandomString(num int) string {
str := "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"
bytes := []byte(str)
@@ -62,44 +61,20 @@ func GetRandomString(num int) string {
return string(result)
}
-/**
- * 判断文件是否存在 存在返回 true 不存在返回false
- */
+// CheckFileIsExist 判断文件是否存在 存在返回 true 不存在返回false
func CheckFileIsExist(filename string) bool {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return false
- } else {
- return true
}
+ return true
}
-// 关闭网关服务,重启读取配置文件
+// Stop 关闭网关服务,重启读取配置文件
func Stop() bool {
id := os.Getpid()
cmd := exec.Command("/bin/bash", "-c", "kill -HUP "+strconv.Itoa(id))
if _, err := cmd.Output(); err != nil {
return false
- } else {
- return true
- }
-}
-
-// 获取MAC地址
-func GetMac() (bool, string) {
- interfaces, err := net.Interfaces()
- if err != nil {
- return false, "Poor soul, here is what you got: " + err.Error()
- }
- for _, inter := range interfaces {
- mac := inter.HardwareAddr //获取本机MAC地址
- m := fmt.Sprintf("%s", mac)
- match, err := regexp.MatchString(`[0-9a-f][0-9a-f][:-][0-9a-f][0-9a-f][:-][0-9a-f][0-9a-f][:-][0-9a-f][0-9a-f][:-][0-9a-f][0-9a-f][:-][0-9a-f][0-9a-f]`, m)
- if err != nil {
- return false, ""
- }
- if match {
- return true, string(m)
- }
}
- return false, ""
+ return true
}
diff --git a/utils/mail.go b/utils/mail.go
index 4b1fda4..a5d8af3 100644
--- a/utils/mail.go
+++ b/utils/mail.go
@@ -8,7 +8,7 @@ import (
"strings"
)
-var period map[string]string = map[string]string{
+var period = map[string]string{
"0": "1",
"1": "5",
"2": "15",
@@ -16,31 +16,32 @@ var period map[string]string = map[string]string{
"4": "60",
}
+//SendToMail 发送邮件
func SendToMail(user, password, host, to, subject, body, mailtype, smtpProtocol string) error {
hp := strings.Split(host, ":")
auth := smtp.PlainAuth("", user, password, hp[0])
- send_to := strings.Split(to, ",")
- if len(send_to) < 2 {
- if send_to[0] == "" {
+ sendTo := strings.Split(to, ",")
+ if len(sendTo) < 2 {
+ if sendTo[0] == "" {
return nil
}
}
log.Debug(user, password, auth)
- var content_type string
+ var contentType string
if mailtype == "html" {
- content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
+ contentType = "Content-Type: text/" + mailtype + "; charset=UTF-8"
} else {
- content_type = "Content-Type: text/plain" + "; charset=UTF-8"
+ contentType = "Content-Type: text/plain" + "; charset=UTF-8"
}
var err error
- msg := []byte("To: " + to + "\r\nFrom: " + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
+ msg := []byte("To: " + to + "\r\nFrom: " + user + ">\r\nSubject: " + subject + "\r\n" + contentType + "\r\n\r\n" + body)
log.Debug("SendToMail", msg)
if smtpProtocol != "0" {
err = SendMailUsingTLS(
host,
auth,
user,
- send_to,
+ sendTo,
msg,
)
if err != nil {
@@ -49,21 +50,21 @@ func SendToMail(user, password, host, to, subject, body, mailtype, smtpProtocol
host,
nil,
user,
- send_to,
+ sendTo,
msg,
)
}
} else {
- err = smtp.SendMail(host, auth, user, send_to, msg)
+ err = smtp.SendMail(host, auth, user, sendTo, msg)
if err != nil {
- err = smtp.SendMail(host, nil, user, send_to, msg)
+ err = smtp.SendMail(host, nil, user, sendTo, msg)
}
}
return err
}
-//return a smtp client
+//Dial return a smtp client
func Dial(addr string) (*smtp.Client, error) {
conn, err := tls.Dial("tcp", addr, nil)
if err != nil {
@@ -74,7 +75,7 @@ func Dial(addr string) (*smtp.Client, error) {
return smtp.NewClient(conn, host)
}
-//参考net/smtp的func SendMail()
+//SendMailUsingTLS 参考net/smtp的func SendMail()
//使用net.Dial连接tls(ssl)端口时,smtp.NewClient()会卡住且不提示err
//len(to)>1时,to[1]开始提示是密送
func SendMailUsingTLS(addr string, auth smtp.Auth, from string,
diff --git a/utils/request.go b/utils/request.go
index 7644fbe..cbd164f 100644
--- a/utils/request.go
+++ b/utils/request.go
@@ -9,7 +9,7 @@ import (
"time"
)
-// 检查插件是否可用
+//CheckPluginIsAvailiable 检查插件是否可用
func CheckPluginIsAvailiable(pluginName string, nodeList []map[string]interface{}) (bool, []map[string]interface{}) {
errNodeList := make([]map[string]interface{}, 0)
for _, v := range nodeList {
@@ -19,7 +19,7 @@ func CheckPluginIsAvailiable(pluginName string, nodeList []map[string]interface{
client := &http.Client{
Timeout: time.Second * 15,
}
- var data url.Values = url.Values{}
+ var data = url.Values{}
data.Add("pluginName", pluginName)
request, err := http.NewRequest("POST", "http://"+v["nodeIP"].(string)+":"+v["nodePort"].(string)+"/goku-check_plugin", strings.NewReader(data.Encode()))
@@ -54,8 +54,8 @@ func CheckPluginIsAvailiable(pluginName string, nodeList []map[string]interface{
continue
}
resp.Body.Close()
- var bodyJson map[string]string
- err = json.Unmarshal(body, &bodyJson)
+ var bodyJSON map[string]string
+ err = json.Unmarshal(body, &bodyJSON)
if err != nil {
errNode := map[string]interface{}{
"nodeAddress": v["nodeIP"].(string) + ":" + v["nodePort"].(string),
@@ -65,7 +65,7 @@ func CheckPluginIsAvailiable(pluginName string, nodeList []map[string]interface{
errNodeList = append(errNodeList, errNode)
continue
}
- if _, ok := bodyJson["statusCode"]; !ok {
+ if _, ok := bodyJSON["statusCode"]; !ok {
errNode := map[string]interface{}{
"nodeAddress": v["nodeIP"].(string) + ":" + v["nodePort"].(string),
"error": "[ERROR] Fail to get statusCode",
@@ -74,11 +74,11 @@ func CheckPluginIsAvailiable(pluginName string, nodeList []map[string]interface{
errNodeList = append(errNodeList, errNode)
continue
}
- if bodyJson["statusCode"] != "000000" {
+ if bodyJSON["statusCode"] != "000000" {
errNode := map[string]interface{}{
"nodeAddress": v["nodeIP"].(string) + ":" + v["nodePort"].(string),
- "error": bodyJson["resultDesc"],
- "errorStatusCode": bodyJson["statusCode"],
+ "error": bodyJSON["resultDesc"],
+ "errorStatusCode": bodyJSON["statusCode"],
}
errNodeList = append(errNodeList, errNode)
continue
@@ -86,7 +86,6 @@ func CheckPluginIsAvailiable(pluginName string, nodeList []map[string]interface{
}
if len(errNodeList) > 0 {
return false, errNodeList
- } else {
- return true, errNodeList
}
+ return true, errNodeList
}
diff --git a/utils/ssh.go b/utils/ssh.go
index 1f78ab8..fd0ff3c 100644
--- a/utils/ssh.go
+++ b/utils/ssh.go
@@ -8,6 +8,7 @@ import (
// "io/ioutil"
)
+//Connect ssh连接
func Connect(user, password, host, key string, port int, cipherList []string) (*ssh.Session, error) {
var (
auth []ssh.AuthMethod
@@ -23,11 +24,6 @@ func Connect(user, password, host, key string, port int, cipherList []string) (*
if key == "" {
auth = append(auth, ssh.Password(password))
} else {
- // pemBytes, err := ioutil.ReadFile(key)
- // if err != nil {
- // return nil, err
- // }
- // fmt.Println(key)
pemBytes := []byte(key)
var signer ssh.Signer
diff --git a/utils/string.go b/utils/string.go
index b7361a9..52892a1 100644
--- a/utils/string.go
+++ b/utils/string.go
@@ -2,6 +2,7 @@ package utils
import "strings"
+//TrimPrefixAll trimPerfixAll
func TrimPrefixAll(s string, r string) string {
for strings.HasPrefix(s, r) {
@@ -9,6 +10,8 @@ func TrimPrefixAll(s string, r string) string {
}
return s
}
+
+//TrimSuffixAll trimSuffixAll
func TrimSuffixAll(s string, r string) string {
for strings.HasSuffix(s, r) {
diff --git a/utils/uuid.go b/utils/uuid.go
index 3fff6e8..9ca6f5d 100644
--- a/utils/uuid.go
+++ b/utils/uuid.go
@@ -6,6 +6,7 @@ import (
"strings"
)
+//TimeUUID uuid
func TimeUUID() string {
out, err := exec.Command("uuidgen").Output()
if err != nil {