提交 5f3f600e 编写于 作者: E eoLinker API Management

V2.0.0

上级 86be5da7
...@@ -18,27 +18,31 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署, ...@@ -18,27 +18,31 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署,
4. **权限管理**:可针对不同策略组设置流量控制策略,包括访问QPS、访问总次数、访问IP、访问时间段等 4. **权限管理**:可针对不同策略组设置流量控制策略,包括访问QPS、访问总次数、访问IP、访问时间段等
5. **请求转发**:默认支持http rest路由。 5. **请求转发**:默认支持http路由。
6. **IP黑白名单**:支持用户的IP白名单、黑名单机制 6. **IP黑白名单**:支持全局IP白名单、也可自定义某个接口的IP白名单
7. **数据整形**:支持参数的转换与绑定。 7. **数据整形**:支持参数的转换与绑定,支持formdata、raw数据、json
8. **监控面板**:清晰的监控界面,方便API网关管理员了解系统主要运行情况 8. **配置文件**:支持配置文件修改网关配置
9. **动态数据更新**:API、插件等都支持在管理平台进行配置,服务器不用重启就可直接生效 9. **快速部署**:支持手动部署与Docker部署
10. **UI界面管理**:完全的图像化界面管理,网关管理员可对多个业务API网关进行管理。 ## Roadmap
11. **快速部署**:支持手动部署与Docker部署 1. **UI界面**:支持通过UI界面修改网关配置
## 预告 2. **API支持**:支持通过API对网关进行操作。
1. **兼容eoLinker-AMS**:可与国内最大的接口管理平台打通。 3. **兼容eoLinker-AMS**:可与国内最大的接口管理平台打通。
2. **告警设置**:当系统达到预设告警条件时,邮件通知运维人员 4. **支持Restful**:支持rest路由
3. **……** 6. **告警设置**:当系统达到预设告警条件时,邮件通知运维人员。
7. **超时设置**:配置访问超时时间,网关控制超时后立即返回,防止系统雪崩。
**……**
## 图片介绍 ## 图片介绍
...@@ -53,9 +57,6 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署, ...@@ -53,9 +57,6 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署,
* go 1.8及以上版本 * go 1.8及以上版本
* redis2.8.x及以上版本
## 相关链接 ## 相关链接
* 官方网站:https://agw.eolinker.com * 官方网站:https://agw.eolinker.com
...@@ -66,8 +67,6 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署, ...@@ -66,8 +67,6 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署,
* Coding:https://git.coding.net/eolinker/Goku-API-Gateway.git * Coding:https://git.coding.net/eolinker/Goku-API-Gateway.git
* Docker:https://hub.docker.com/r/eolinker/goku-api-gateway-ce
* 教程文档:http://help.eolinker.com/agw * 教程文档:http://help.eolinker.com/agw
* 官方交流Q群:[用户交流1群](https://jq.qq.com/?_wv=1027&k=5ikfC2S)(群号:725853895) * 官方交流Q群:[用户交流1群](https://jq.qq.com/?_wv=1027&k=5ikfC2S)(群号:725853895)
...@@ -111,4 +110,16 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署, ...@@ -111,4 +110,16 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署,
#### V1.0.3(2018/4/20) #### V1.0.3(2018/4/20)
修复: 修复:
1. 修复“鉴权方式”编辑页错位问题。 1. 修复“鉴权方式”编辑页错位问题。
\ No newline at end of file
#### V2.0.0(2018/5/4)
新增:
1. 通过配置文件修改网关配置;
2. 新增全局IP黑白名单;
3. 参数新增支持json类型。
优化:
1. 架构优化,减少第三方依赖,提升网关性能;
2. 弃置mysql、redis数据库的使用,改用配置文件方式读取文件配置。
\ No newline at end of file
package conf
import (
"encoding/json"
"io/ioutil"
"os"
)
var (
Configure map[string]string
)
func init() {
Configure = make(map[string]string)
}
func ReadConfigure(filepath string) (err error) {
file, err := os.Open(filepath)
if err != nil {
return
}
content, err := ioutil.ReadAll(file)
if err != nil {
return
}
err = json.Unmarshal(content, &Configure)
return
}
package controller
import (
"goku-ce-1.0/dao"
"goku-ce-1.0/utils"
"net/http"
"strings"
"time"
"fmt"
"github.com/farseer810/requests"
"github.com/farseer810/yawf"
)
func CreateRequest(httpRequest *http.Request, info *utils.MappingInfo, queryParams yawf.QueryParams,
formParams yawf.FormParams, httpResponse http.ResponseWriter, context yawf.Context) (int, []byte) {
t1 := time.Now()
var backendDomain string
if info.BackendProtocol == "0" {
backendDomain = "http://" + info.BackendURI + info.BackendPath
} else {
backendDomain = "https://" + info.BackendURI + info.BackendPath
}
session := requests.NewSession()
request, err := session.Method(info.BackendRequestType, backendDomain)
if err != nil {
panic(err)
}
var backendHeaders map[string][]string = make(map[string][]string)
var backendQueryParams map[string][]string = make(map[string][]string)
var backendFormParams map[string][]string = make(map[string][]string)
for _, reqParam := range info.RequestParams {
var param []string
switch reqParam.ParamPosition {
case "header":
param = httpRequest.Header[reqParam.ParamKey]
case "body":
if httpRequest.Method == "POST" || httpRequest.Method == "PUT" || httpRequest.Method == "PATCH" {
param = formParams[reqParam.ParamKey]
} else {
continue
}
case "query":
param = queryParams[reqParam.ParamKey]
}
if param == nil {
if reqParam.IsNotNull {
// missing required parameters
return 400, []byte("missing required parameters")
} else {
continue
}
}
switch reqParam.BackendParamPosition {
case "header":
backendHeaders[reqParam.BackendParamKey] = param
case "body":
if info.BackendRequestType == "POST" || info.BackendRequestType == "PUT" || info.BackendRequestType == "PATCH" {
backendFormParams[reqParam.BackendParamKey] = param
}
case "query":
backendQueryParams[reqParam.BackendParamKey] = param
}
}
for _, constParam := range info.ConstantParams {
switch constParam.ParamPosition {
case "header":
backendHeaders[constParam.BackendParamKey] = []string{constParam.ParamValue}
case "body":
if info.BackendRequestType == "POST" || info.BackendRequestType == "PUT" || info.BackendRequestType == "PATCH" {
backendFormParams[constParam.BackendParamKey] = []string{constParam.ParamValue}
} else {
backendQueryParams[constParam.BackendParamKey] = []string{constParam.ParamValue}
}
}
}
for key, values := range backendHeaders {
request.SetHeader(key, values...)
}
for key, values := range backendQueryParams {
request.SetQueryParam(key, values...)
}
for key, values := range backendFormParams {
request.SetFormParam(key, values...)
}
cookies := make(map[string]string)
for _, cookie := range httpRequest.Cookies() {
cookies[cookie.Name] = cookie.Value
}
session.SetCookies(cookies)
index := strings.Index(httpRequest.RemoteAddr, ":")
remoteIP := httpRequest.RemoteAddr[:index]
fmt.Println("deal with param time:",time.Since(t1))
t2 := time.Now()
res, err := request.Send()
fmt.Println("get response time:",time.Since(t2))
if err != nil {
dao.UpdateVisitCount(context, info,remoteIP)
dao.UpdateFailureCount(context,info.GatewayHashKey)
return 404,[]byte("fail to get reply")
}
httpResponseHeader := httpResponse.Header()
for key, _ := range httpResponseHeader {
httpResponseHeader[key] = nil
}
for key, values := range res.Headers() {
httpResponseHeader[key] = values
}
t3 := time.Now()
go dao.UpdateVisitCount(context, info,remoteIP)
fmt.Println("update visit count:",time.Since(t3))
t4 := time.Now()
statusCode := res.StatusCode()
if statusCode == 200 {
go dao.UpdateSuccessCount(context,info.GatewayHashKey)
}else{
go dao.UpdateFailureCount(context,info.GatewayHashKey)
}
fmt.Println("update success/failure count:",time.Since(t4))
return res.StatusCode(), res.Body()
}
package dao
import (
"goku-ce-1.0/dao/cache"
"github.com/farseer810/yawf"
"github.com/garyburd/redigo/redis"
"goku-ce-1.0/dao/database"
"strconv"
"goku-ce-1.0/utils"
)
func GetAllAPIPaths(context yawf.Context, gatewayHashKey string) []string {
result := getAllAPIPathsFromCache(context, gatewayHashKey)
return result
}
func getAllAPIPathsFromCache(context yawf.Context, gatewayHashKey string) []string {
conn := cache.GetConnection(context)
var redisKey string = "apiList:" + gatewayHashKey
result, err := redis.Strings(conn.Do("LRANGE", redisKey, 0, -1))
if err != nil {
panic(err)
}else if len(result) == 0{
result = loadAllAPIPathFromDB(gatewayHashKey)
}
return result
}
func loadAllAPIPathFromDB(gatewayHashkey string) []string {
db := database.GetConnection()
sql := "SELECT gatewayProtocol, gatewayRequestType, gatewayRequestURI FROM eo_gateway_api INNER JOIN eo_gateway ON eo_gateway_api.gatewayID = eo_gateway.gatewayID WHERE eo_gateway.hashkey = ?;"
apiList := make([]string,0)
rows,err := db.Query(sql,gatewayHashkey)
if err != nil {
return apiList
}
defer rows.Close()
for rows.Next(){
var gatewayProtocol,gatewayRequestType int
var gatewayRequestURI string
err = rows.Scan(&gatewayProtocol,&gatewayRequestType,&gatewayRequestURI)
if err != nil {
break
}
api := strconv.Itoa(gatewayProtocol) + ":" + strconv.Itoa(gatewayRequestType) + ":" + gatewayRequestURI
apiList = append(apiList,api)
}
redisConn,err := utils.GetRedisConnection()
listName := "apiList:" + gatewayHashkey
for _,i := range apiList {
_ ,err := redisConn.Do("rpush",listName,i)
if err != nil{
panic(err)
}
}
return apiList
}
package cache
import (
"goku-ce-1.0/conf"
_ "goku-ce-1.0/utils"
"strconv"
"github.com/codegangsta/inject"
"github.com/farseer810/yawf"
redis "github.com/garyburd/redigo/redis"
)
var (
pool *redis.Pool
)
func init() {
pool = redis.NewPool(dial(), 2000)
}
func dial() func() (redis.Conn, error) {
db, err := strconv.Atoi(conf.Configure["redis_db"])
if err != nil {
db = 0
}
if _, hasPassword := conf.Configure["redis_password"]; hasPassword {
return func() (redis.Conn, error) {
return redis.Dial("tcp",
conf.Configure["redis_host"]+":"+conf.Configure["redis_port"],
redis.DialPassword(conf.Configure["redis_password"]),
redis.DialDatabase(db))
}
} else {
return func() (redis.Conn, error) {
return redis.Dial("tcp",
conf.Configure["redis_host"]+":"+conf.Configure["redis_port"],
redis.DialDatabase(db))
}
}
}
func getConnection() redis.Conn {
return pool.Get()
}
func GetConnectionFromContext(context yawf.Context) redis.Conn {
var conn redis.Conn = nil
value := context.Get(inject.InterfaceOf((*redis.Conn)(nil)))
if value.IsValid() {
conn = value.Interface().(redis.Conn)
}
return conn
}
func GetConnection(context yawf.Context) redis.Conn {
conn := GetConnectionFromContext(context)
if conn != nil {
return conn
}
conn = getConnection()
context.MapTo(conn, (*redis.Conn)(nil))
return conn
}
package database
import (
"goku-ce-1.0/conf"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
var (
db *sql.DB
)
func init() {
var err error
var dsn string = conf.Configure["mysql_username"] + ":" + conf.Configure["mysql_password"]
dsn = dsn + "@tcp(" + conf.Configure["mysql_host"] + ":" + conf.Configure["mysql_port"] + ")/" + conf.Configure["mysql_dbname"]
dsn = dsn + "?charset=utf8"
db, err = sql.Open("mysql", dsn)
if err == nil {
db.SetMaxOpenConns(2000)
db.SetMaxIdleConns(1000)
} else {
panic(err)
}
}
func GetConnection() *sql.DB {
return db
}
package dao
import (
"goku-ce-1.0/dao/cache"
"github.com/farseer810/yawf"
"github.com/garyburd/redigo/redis"
"goku-ce-1.0/dao/database"
)
func loadGatewayHashKey(gatewayAlias string) string{
db := database.GetConnection()
var gatewayHashKey string
sql := `SELECT hashKey FROM eo_gateway WHERE gatewayAlias = ?; `
err := db.QueryRow(sql,gatewayAlias).Scan(&gatewayHashKey)
if err != nil {
panic(err)
}
return gatewayHashKey
}
func GetGatewayHashKey(context yawf.Context,gatewayAlias string) string {
var redisKey string = "gatewayHashKey:" + gatewayAlias
conn := cache.GetConnection(context)
gatewayHashKey, err := redis.String(conn.Do("GET", redisKey))
if err == redis.ErrNil {
gatewayHashKey = loadGatewayHashKey(gatewayAlias)
conn.Do("SET", redisKey, gatewayHashKey)
} else if err != nil {
panic(err)
}
return gatewayHashKey
}
package dao
import (
"encoding/json"
"goku-ce-1.0/dao/cache"
"goku-ce-1.0/dao/database"
"goku-ce-1.0/utils"
"fmt"
"strings"
"github.com/farseer810/yawf"
"github.com/garyburd/redigo/redis"
)
func loadGatewayIPList(context yawf.Context, hashKey,strategyKey string) (*utils.IPListInfo,bool) {
var ipList []string
var blackList string
var whiteList string
var chooseType int
var info *utils.IPListInfo = &utils.IPListInfo{}
flag := true
db := database.GetConnection()
sql := `SELECT chooseType,IFNULL(blackList,''),IFNULL(whiteList,'') FROM eo_gateway_strategy_group WHERE ` +
`gatewayID=(SELECT gatewayID FROM eo_gateway WHERE hashKey=? AND strategyKey = ?) `
err := db.QueryRow(sql, hashKey,strategyKey).Scan(&chooseType, &blackList, &whiteList)
if err != nil {
panic(err)
flag =false
}else{
if chooseType == 1 {
blackList = strings.Replace(blackList,";",";",-1)
ipList = strings.Split(blackList,";")
} else if chooseType == 2 {
whiteList = strings.Replace(whiteList,";",";",-1)
ipList = strings.Split(whiteList,";")
} else {
ipList = []string{}
}
info.IPList = ipList
info.ChooseType = chooseType
}
return info,flag
}
func getGatewayIPList(context yawf.Context, hashKey,strategyKey string) *utils.IPListInfo {
var redisKey string = "IPList:" + hashKey + ":" + strategyKey
var info *utils.IPListInfo
fmt.Println(hashKey)
conn := cache.GetConnection(context)
infoStr, err := redis.String(conn.Do("GET", redisKey))
if err == redis.ErrNil {
ipInfo,flag := loadGatewayIPList(context, hashKey,strategyKey)
if flag{
infoStr = ipInfo.String()
// 缓存时间为1 hour
conn.Do("SET", redisKey, infoStr, "EX", 3600)
}
info = ipInfo
} else if err != nil {
panic(err)
} else {
info = &utils.IPListInfo{}
err = json.Unmarshal([]byte(infoStr), &info)
if err != nil {
panic(err)
}
}
return info
}
func GetIPList(context yawf.Context, hashKey,strategyKey string) *utils.IPListInfo {
return getGatewayIPList(context, hashKey,strategyKey)
}
package dao
import (
"encoding/json"
"goku-ce-1.0/dao/cache"
"goku-ce-1.0/dao/database"
"goku-ce-1.0/utils"
"fmt"
"strconv"
"strings"
"github.com/farseer810/yawf"
"github.com/garyburd/redigo/redis"
)
func loadMappingInfo(hashKey string, matchedURI string) *utils.MappingInfo {
var apiID int
var jsonStr,path string
parsedArray := strings.Split(matchedURI, ":")
protocol, method, uri := parsedArray[0], parsedArray[1], parsedArray[2]
fmt.Println(protocol, method, uri, hashKey)
db := database.GetConnection()
sql := `SELECT apiID FROM eo_gateway_api WHERE ` +
`gatewayID=(SELECT gatewayID FROM eo_gateway WHERE hashKey=?) ` +
`and gatewayProtocol=? and gatewayRequestType=? and gatewayRequestURI=?`
iProtocol, _ := strconv.Atoi(protocol)
iMethod, _ := strconv.Atoi(method)
err := db.QueryRow(sql, hashKey, iProtocol, iMethod, uri).Scan(&apiID)
if err != nil {
panic(err)
}
fmt.Println(apiID)
sql = `SELECT apiJson,path FROM eo_gateway_api_cache WHERE apiID=?`
err = db.QueryRow(sql, apiID).Scan(&jsonStr,&path)
if err != nil {
panic(err)
}
fmt.Println(jsonStr)
info := utils.ParseDBJson(jsonStr,path)
info.ApiID = apiID
return info
}
func getMapping(context yawf.Context, hashKey string, matchedURI string) *utils.MappingInfo {
var redisKey string = "apiInfo:" + hashKey + ":" + matchedURI
var info *utils.MappingInfo
conn := cache.GetConnection(context)
infoStr, err := redis.String(conn.Do("GET", redisKey))
if err == redis.ErrNil {
info = loadMappingInfo(hashKey, matchedURI)
infoStr = info.String()
// 缓存时间为1 hour
conn.Do("SET", redisKey, infoStr, "EX", 3600)
} else if err != nil {
panic(err)
} else {
info = &utils.MappingInfo{}
err = json.Unmarshal([]byte(infoStr), &info)
if err != nil {
panic(err)
}
}
return info
}
func GetMapping(context yawf.Context, hashKey string, matchedURI string) *utils.MappingInfo {
return getMapping(context, hashKey, matchedURI)
}
package dao
import (
"goku-ce-1.0/utils"
"strconv"
"time"
"github.com/farseer810/yawf"
)
// 更新访问次数
func UpdateVisitCount(context yawf.Context, info *utils.MappingInfo,remoteIP string) {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
var redisKey string = "gatewayDayCount:" + info.GatewayHashKey + ":" + dateStr
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
if err != nil{
panic(err)
}
// 更新网关当日访问次数
redisConn.Do("INCR", redisKey)
// 更新网关实时访问次数
timeStr := dateStr + "-" + strconv.Itoa(now.Hour()) + "-" + strconv.Itoa(now.Minute())
redisKey = "gatewayMinuteCount:" + info.GatewayHashKey + ":" + timeStr
redisConn.Do("INCR", redisKey)
// 更新当日网关策略访问次数
redisKey = "gatewayStrategyDayCount:" + info.GatewayHashKey + ":" + info.StrategyKey + ":" + dateStr
redisConn.Do("INCR", redisKey)
// 更新实时访问次数
redisKey = "gatewayStrategyMinuteCount:" + info.GatewayHashKey + ":" + info.StrategyKey + ":" + timeStr
redisConn.Do("INCR", redisKey)
// 更新当日网关策略IP访问次数
redisKey = "gatewayStrategy:" + info.GatewayHashKey + ":" + info.StrategyKey + ":IPDayCount:" + dateStr + ":" + remoteIP
redisConn.Do("INCR", redisKey)
// 更新网关策略IP访问次数(小时)
redisKey = "gatewayStrategy:" + info.GatewayHashKey + ":" + info.StrategyKey + ":IPHourCount:" + dateStr + "-" + strconv.Itoa(now.Hour()) + ":" + remoteIP
redisConn.Do("INCR", redisKey)
// 更新网关策略IP访问次数(分钟)
redisKey = "gatewayStrategy:" + info.GatewayHashKey + ":" + info.StrategyKey + ":IPMinuteCount:" + timeStr + ":" + remoteIP
redisConn.Do("INCR", redisKey)
// 更新网关策略IP访问次数(秒)
redisKey = "gatewayStrategy:" + info.GatewayHashKey + ":" + info.StrategyKey + ":IPSecondCount:" + timeStr + "-" + strconv.Itoa(now.Second()) + ":" + remoteIP
redisConn.Do("INCR", redisKey)
}
// 更新成功次数
func UpdateSuccessCount(context yawf.Context, gatewayHashKey string) {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
var redisKey string = "gatewaySuccessCount:" + gatewayHashKey + ":" + dateStr
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
if err != nil{
panic(err)
}
redisConn.Do("INCR", redisKey)
}
// 更新失败次数
func UpdateFailureCount(context yawf.Context,gatewayHashKey string) {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
var redisKey string = "gatewayFailureCount:" + gatewayHashKey + ":" + dateStr
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
if err != nil{
panic(err)
}
redisConn.Do("INCR", redisKey)
}
\ No newline at end of file
package dao
import (
"goku-ce-1.0/dao/cache"
"goku-ce-1.0/utils"
"strconv"
"time"
"goku-ce-1.0/dao/database"
"github.com/farseer810/yawf"
"github.com/garyburd/redigo/redis"
"encoding/json"
"fmt"
)
// 获取网关当日访问次数
func GetGatewayDayVisitCount(context yawf.Context, info *utils.MappingInfo) int {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
var redisKey string = "gatewayDayCount:" + info.GatewayHashKey + ":" + dateStr
conn := cache.GetConnection(context)
count, err := redis.Int(conn.Do("GET", redisKey))
if err == redis.ErrNil {
return 0
} else if err != nil {
panic(err)
}
return count
}
// 获取网关实时访问次数(精确到分钟)
func GetGatewayMinuteCount(context yawf.Context, info *utils.MappingInfo) int {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
timeStr := dateStr + "-" + strconv.Itoa(now.Hour()) + "-" + strconv.Itoa(now.Minute())
var redisKey string = "gatewayMinuteCount:" + info.GatewayHashKey + ":" + timeStr
conn := cache.GetConnection(context)
count, err := redis.Int(conn.Do("GET", redisKey))
if err == redis.ErrNil {
return 0
} else if err != nil {
panic(err)
}
return count
}
// 获取当天网关策略组访问次数
func GetGatewayStrategyDayCount(context yawf.Context, info *utils.MappingInfo) int {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
var redisKey string = "gatewayStrategy:" + info.GatewayHashKey + ":" + info.StrategyKey + ":" + dateStr
conn := cache.GetConnection(context)
count, err := redis.Int(conn.Do("GET", redisKey))
if err == redis.ErrNil {
return 0
} else if err != nil {
panic(err)
}
return count
}
// 获取实时网关策略组访问次数
func GetGatewayStrategyMinuteCount(context yawf.Context, info *utils.MappingInfo) int {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
timeStr := dateStr + "-" + strconv.Itoa(now.Hour()) + "-" + strconv.Itoa(now.Minute())
var redisKey string = "gatewayStrategy:" + info.GatewayHashKey + ":" + info.StrategyKey + ":" + timeStr
conn := cache.GetConnection(context)
count, err := redis.Int(conn.Do("GET", redisKey))
if err == redis.ErrNil {
return 0
} else if err != nil {
panic(err)
}
return count
}
// 获取当天IP访问网关策略次数
func GetGatewayStrategyIPDayCount(context yawf.Context,gatewayHashKey,strategyKey, remoteIP string) int {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
var redisKey string = "gatewayStrategy:" + gatewayHashKey + ":" + strategyKey + ":IPDayCount:" + dateStr + ":" + remoteIP
conn := cache.GetConnection(context)
count, err := redis.Int(conn.Do("GET", redisKey))
if err == redis.ErrNil {
return -1
} else if err != nil {
panic(err)
}
return count
}
// 获取当前IP访问网关策略次数(小时)
func GetGatewayStrategyIPHourCount(context yawf.Context,gatewayHashKey,strategyKey, remoteIP string) int {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
timeStr := dateStr + "-" + strconv.Itoa(now.Hour())
var redisKey string = "gatewayStrategy:" + gatewayHashKey + ":" + strategyKey + ":IPHourCount:" + timeStr + ":" + remoteIP
conn := cache.GetConnection(context)
count, err := redis.Int(conn.Do("GET", redisKey))
if err == redis.ErrNil {
return -1
} else if err != nil {
panic(err)
}
return count
}
// 获取当前IP访问网关策略次数(分钟)
func GetGatewayStrategyIPMinuteCount(context yawf.Context,gatewayHashKey,strategyKey, remoteIP string) int {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
timeStr := dateStr + "-" + strconv.Itoa(now.Hour()) + "-" + strconv.Itoa(now.Minute())
var redisKey string = "gatewayStrategy:" + gatewayHashKey + ":" + strategyKey + ":IPMinuteCount:" + timeStr + ":" + remoteIP
conn := cache.GetConnection(context)
count, err := redis.Int(conn.Do("GET", redisKey))
if err == redis.ErrNil {
return -1
} else if err != nil {
panic(err)
}
return count
}
// 获取当前IP访问网关策略次数(秒)
func GetGatewayStrategyIPSecondCount(context yawf.Context,gatewayHashKey,strategyKey, remoteIP string) int {
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
timeStr := dateStr + "-" + strconv.Itoa(now.Hour()) + "-" + strconv.Itoa(now.Minute()) + "-" + strconv.Itoa(now.Second())
var redisKey string = "gatewayStrategy:" + gatewayHashKey + ":" + strategyKey + ":IPSecondCount:" + timeStr + ":" + remoteIP
conn := cache.GetConnection(context)
count, err := redis.Int(conn.Do("GET", redisKey))
if err == redis.ErrNil {
return -1
} else if err != nil {
panic(err)
}
return count
}
// 加载策略组秒阀值
func loadStrategySecondValve(strategyKey string) utils.RateLimitInfo{
now := time.Now()
db := database.GetConnection()
sql := "SELECT intervalType,viewType,limitCount,priorityLevel FROM eo_gateway_rate_limit INNER JOIN eo_gateway_strategy_group ON eo_gateway_rate_limit.strategyID = eo_gateway_strategy_group.strategyID WHERE eo_gateway_strategy_group.strategyKey = ? AND intervalType = 0 AND (HOUR(startTime) <= ? AND HOUR(endTime) > ?) OR (HOUR(startTime) > HOUR(endTime) AND HOUR(startTime) <= ? AND HOUR(endTime) > ?) ORDER BY priorityLevel DESC"
hour := now.Hour()
var rateLimitInfo utils.RateLimitInfo
err := db.QueryRow(sql,strategyKey,hour,hour,hour,hour+24).Scan(&rateLimitInfo.IntervalType,&rateLimitInfo.ViewType,&rateLimitInfo.LimitCount,&rateLimitInfo.PriorityLevel)
if err != nil{
rateLimitInfo.ViewType = 0
rateLimitInfo.IntervalType = 0
rateLimitInfo.LimitCount = -1
rateLimitInfo.PriorityLevel = 1
}
return rateLimitInfo
}
// 加载策略组分阀值
func loadStrategyMinuteValve(strategyKey string) utils.RateLimitInfo {
now := time.Now()
db := database.GetConnection()
sql := "SELECT intervalType,viewType,limitCount,priorityLevel FROM eo_gateway_rate_limit INNER JOIN eo_gateway_strategy_group ON eo_gateway_rate_limit.strategyID = eo_gateway_strategy_group.strategyID WHERE eo_gateway_strategy_group.strategyKey = ? AND intervalType = 1 AND (HOUR(startTime) <= ? AND HOUR(endTime) > ?) OR (HOUR(startTime) > HOUR(endTime) AND HOUR(startTime) <= ? AND HOUR(endTime) > ?) ORDER BY priorityLevel DESC"
hour := now.Hour()
var rateLimitInfo utils.RateLimitInfo
err := db.QueryRow(sql,strategyKey,hour,hour,hour,hour+24).Scan(&rateLimitInfo.IntervalType,&rateLimitInfo.ViewType,&rateLimitInfo.LimitCount,&rateLimitInfo.PriorityLevel)
if err != nil{
rateLimitInfo.ViewType = 0
rateLimitInfo.IntervalType = 1
rateLimitInfo.LimitCount = -1
rateLimitInfo.PriorityLevel = 1
}
return rateLimitInfo
}
// 加载策略组小时阀值
func loadStrategyHourValve(strategyKey string) utils.RateLimitInfo {
now := time.Now()
db := database.GetConnection()
sql := "SELECT intervalType,viewType,limitCount,priorityLevel FROM eo_gateway_rate_limit INNER JOIN eo_gateway_strategy_group ON eo_gateway_rate_limit.strategyID = eo_gateway_strategy_group.strategyID WHERE eo_gateway_strategy_group.strategyKey = ? AND intervalType = 2 AND (HOUR(startTime) <= ? AND HOUR(endTime) > ?) OR (HOUR(startTime) > HOUR(endTime) AND HOUR(startTime) <= ? AND HOUR(endTime) > ?) ORDER BY priorityLevel DESC"
hour := now.Hour()
var rateLimitInfo utils.RateLimitInfo
err := db.QueryRow(sql,strategyKey,hour,hour,hour,hour+24).Scan(&rateLimitInfo.IntervalType,&rateLimitInfo.ViewType,&rateLimitInfo.LimitCount,&rateLimitInfo.PriorityLevel)
if err != nil{
rateLimitInfo.ViewType = 0
rateLimitInfo.IntervalType = 2
rateLimitInfo.LimitCount = -1
rateLimitInfo.PriorityLevel = 1
}
return rateLimitInfo
}
// 加载策略组天阀值
func loadStrategyDayValve(strategyKey string) utils.RateLimitInfo {
now := time.Now()
db := database.GetConnection()
sql := "SELECT intervalType,viewType,limitCount,priorityLevel,startTime,endTime FROM eo_gateway_rate_limit INNER JOIN eo_gateway_strategy_group ON eo_gateway_rate_limit.strategyID = eo_gateway_strategy_group.strategyID WHERE eo_gateway_strategy_group.strategyKey = ? AND intervalType = 3 AND (HOUR(startTime) <= ? AND HOUR(endTime) > ?) OR (HOUR(startTime) > HOUR(endTime) AND HOUR(startTime) <= ? AND HOUR(endTime) > ?) ORDER BY priorityLevel DESC"
hour := now.Hour()
var rateLimitInfo utils.RateLimitInfo
err := db.QueryRow(sql,strategyKey,hour,hour,hour,hour+24).Scan(&rateLimitInfo.IntervalType,&rateLimitInfo.ViewType,&rateLimitInfo.LimitCount,&rateLimitInfo.PriorityLevel,&rateLimitInfo.StartTime,&rateLimitInfo.EndTime)
if err != nil{
rateLimitInfo.ViewType = 0
rateLimitInfo.IntervalType = 3
rateLimitInfo.LimitCount = -1
rateLimitInfo.PriorityLevel = 1
rateLimitInfo.StartTime = "00:00"
rateLimitInfo.EndTime = "00:00"
}
return rateLimitInfo
}
// 获取策略组秒阀值
func GetStrategySecondValve(context yawf.Context,hashKey,strategyKey string) utils.RateLimitInfo {
now := time.Now()
hour := now.Hour()
var nextHour int
if hour == 23{
nextHour = 0
}else{
nextHour = hour + 1
}
var redisKey string = "gatewayStrategySecondValve:" + hashKey + ":" + strategyKey + ":" + strconv.Itoa(hour) + "-" + strconv.Itoa(nextHour)
var info utils.RateLimitInfo
conn := cache.GetConnection(context)
infoStr, err := redis.String(conn.Do("GET", redisKey))
if err == redis.ErrNil {
info := loadStrategySecondValve(strategyKey)
result, err := json.Marshal(info)
if err != nil {
panic(err)
}
infoStr = string(result)
conn.Do("SET", redisKey, infoStr, "EX", 3600)
} else if err != nil {
panic(err)
} else {
err = json.Unmarshal([]byte(infoStr), &info)
if err != nil {
panic(err)
}
}
return info
}
// 获取策略组分阀值
func GetStrategyMinuteValve(context yawf.Context,hashKey,strategyKey string) utils.RateLimitInfo {
now := time.Now()
hour := now.Hour()
var nextHour int
if hour == 23{
nextHour = 0
}else{
nextHour = hour + 1
}
var redisKey string = "gatewayStrategyMinuteValve:" + hashKey + ":" + strategyKey + ":" + strconv.Itoa(hour) + "-" + strconv.Itoa(nextHour)
var info utils.RateLimitInfo
conn := cache.GetConnection(context)
infoStr, err := redis.String(conn.Do("GET", redisKey))
if err == redis.ErrNil {
info = loadStrategyMinuteValve(strategyKey)
result, err := json.Marshal(info)
if err != nil {
panic(err)
}
infoStr = string(result)
conn.Do("SET", redisKey, infoStr, "EX", 3600)
} else if err != nil {
panic(err)
} else {
err = json.Unmarshal([]byte(infoStr), &info)
if err != nil {
panic(err)
}
}
return info
}
// 获取策略组时阀值
func GetStrategyHourValve(context yawf.Context,hashKey,strategyKey string) utils.RateLimitInfo {
now := time.Now()
hour := now.Hour()
var nextHour int
if hour == 23{
nextHour = 0
}else{
nextHour = hour + 1
}
var redisKey string = "gatewayStrategyHourValve:" + hashKey + ":" + strategyKey + ":" + strconv.Itoa(hour) + "-" + strconv.Itoa(nextHour)
var info utils.RateLimitInfo
conn := cache.GetConnection(context)
infoStr, err := redis.String(conn.Do("GET", redisKey))
if err == redis.ErrNil {
info = loadStrategyHourValve(strategyKey)
result, err := json.Marshal(info)
if err != nil {
panic(err)
}
infoStr = string(result)
conn.Do("SET", redisKey, infoStr, "EX", 3600)
} else if err != nil {
panic(err)
} else {
err = json.Unmarshal([]byte(infoStr), &info)
if err != nil {
panic(err)
}
}
return info
}
// 获取策略组天阀值
func GetStrategyDayValve(context yawf.Context,hashKey,strategyKey string) utils.RateLimitInfo {
now := time.Now()
hour := now.Hour()
var nextHour int
if hour == 23{
nextHour = 0
}else{
nextHour = hour + 1
}
var redisKey string = "gatewayStrategyDayValve:" + hashKey + ":" + strategyKey + ":" + strconv.Itoa(hour) + "-" + strconv.Itoa(nextHour)
fmt.Println(redisKey)
var info utils.RateLimitInfo
conn := cache.GetConnection(context)
infoStr, err := redis.String(conn.Do("GET", redisKey))
if err == redis.ErrNil {
info = loadStrategyDayValve(strategyKey)
result, err := json.Marshal(info)
if err != nil {
panic(err)
}
infoStr = string(result)
conn.Do("SET", redisKey, infoStr, "EX", 3600)
} else if err != nil {
panic(err)
} else {
err = json.Unmarshal([]byte(infoStr), &info)
if err != nil {
panic(err)
}
}
// 如果开始时间不等于结束时间,开始计数
if info.StartTime != info.EndTime{
startTime,_ := time.ParseInLocation("15:06",info.StartTime,time.Local)
endTime,_ := time.ParseInLocation("15:06",info.EndTime,time.Local)
var startHour, endHour int
startHour = startTime.Hour()
if endTime.Minute() >= 1 && endTime.Hour() == 23 {
endHour = 24
}else{
endHour = endTime.Hour()
}
key := "gatewayStrategyPeriodCount:" + hashKey + ":" + strategyKey + ":" + strconv.Itoa(startHour) + "-" +strconv.Itoa(endHour)
conn.Do("INCR", key)
}
return info
}
// 获取当天某一时间段的访问次数
func GetStrategyPeriodCount(context yawf.Context,hashKey,strategyKey,start,end string) int {
startTime,_ := time.ParseInLocation("15:06",start,time.Local)
endTime,_ := time.ParseInLocation("15:06",end,time.Local)
var startHour, endHour int
startHour = startTime.Hour()
if endTime.Minute() >= 1 && endTime.Hour() == 23 {
endHour = 24
}else{
endHour = endTime.Hour()
}
var redisKey string = "gatewayStrategyPeriodCount:" + hashKey + ":" + strategyKey + ":" + strconv.Itoa(startHour) + "-" +strconv.Itoa(endHour)
conn := cache.GetConnection(context)
count, err := redis.Int(conn.Do("GET", redisKey))
if err == redis.ErrNil {
return -1
} else if err != nil {
panic(err)
}
return count
}
\ No newline at end of file
package dao
import (
"goku-ce-1.0/dao/cache"
"goku-ce-1.0/utils"
"goku-ce-1.0/dao/database"
"github.com/farseer810/yawf"
"github.com/garyburd/redigo/redis"
"encoding/json"
"encoding/base64"
)
func loadAuthInfo(strategyKey string) utils.AuthInfo {
var authInfo utils.AuthInfo
db := database.GetConnection()
sql := "SELECT eo_gateway_strategy_group.strategyID,authType,apiKey,userName,userPassword FROM eo_gateway_auth INNER JOIN eo_gateway_strategy_group ON eo_gateway_strategy_group.strategyID = eo_gateway_auth.strategyID WHERE strategyKey = ?;"
err := db.QueryRow(sql,strategyKey).Scan(&authInfo.StrategyID,&authInfo.AuthType,&authInfo.ApiKey,&authInfo.UserName,&authInfo.UserPassword)
if err != nil{
authInfo.AuthType = 2
}
if authInfo.AuthType == 0{
authStr := []byte(authInfo.UserName + ":" + authInfo.UserPassword)
authInfo.Authorization = base64.StdEncoding.EncodeToString(authStr)
}
return authInfo
}
func getAuthInfo(context yawf.Context, hashKey string, strategyKey string) utils.AuthInfo {
var redisKey string = "authInfo:" + hashKey + ":" + strategyKey
var info utils.AuthInfo
conn := cache.GetConnection(context)
infoStr, err := redis.String(conn.Do("GET", redisKey))
if err == redis.ErrNil {
info = loadAuthInfo(strategyKey)
result, err := json.Marshal(info)
if err != nil {
panic(err)
}
infoStr = string(result)
conn.Do("SET", redisKey, infoStr, "EX", 3600)
} else if err != nil {
panic(err)
} else {
err = json.Unmarshal([]byte(infoStr), &info)
if err != nil {
panic(err)
}
}
return info
}
func GetAuthInfo(context yawf.Context, hashKey,strategyKey string) utils.AuthInfo {
return getAuthInfo(context, hashKey,strategyKey)
}
package main
import (
"goku-ce-1.0/server/controller"
"github.com/gin-gonic/gin"
"github.com/fvbock/endless"
// "fmt"
"log"
"os"
)
func main() {
router := gin.Default()
web := router.Group("/Web")
{
guest :=web.Group("/Guest")
{
guest.POST("/login",controller.Login)
}
user :=web.Group("/User")
{
user.POST("/logout",controller.Logout)
user.POST("/editPassword",controller.EditPassword)
user.POST("/checkLogin",controller.CheckLogin)
}
group := web.Group("/Group")
{
group.POST("/addGroup",controller.AddGroup)
group.POST("/editGroup",controller.EditGroup)
group.POST("/deleteGroup",controller.DeleteGroup)
group.POST("/getGroupList",controller.GetGroupList)
group.POST("/getGroupName",controller.GetGroupName)
group.POST("/getGroupListByKeyword",controller.GetGroupListByKeyword)
}
api := web.Group("/Api")
{
api.POST("/addApi",controller.AddApi)
api.POST("/editApi",controller.EditApi)
api.POST("/deleteApi",controller.DeleteApi)
api.POST("/getApiList",controller.GetApiListOrderByName)
api.POST("/getAllApiList",controller.GetAllApiListOrderByName)
api.POST("/getApi",controller.GetApi)
api.POST("/searchApi",controller.SearchApi)
api.POST("/checkGatewayURLIsExist",controller.CheckGatewayURLIsExist)
}
backend := web.Group("/Backend")
{
backend.POST("/addBackend",controller.AddBackend)
backend.POST("/editBackend",controller.EditBackend)
backend.POST("/deleteBackend",controller.DeleteBackend)
backend.POST("/getBackendList",controller.GetBackendList)
backend.POST("/getBackend",controller.GetBackendInfo)
}
gateway := web.Group("/Gateway")
{
gateway.POST("/addGateway",controller.AddGateway)
gateway.POST("/editGateway",controller.EditGateway)
gateway.POST("/deleteGateway",controller.DeleteGateway)
gateway.POST("/getGatewayList",controller.GetGatewayList)
gateway.POST("/getGateway",controller.GetGatewayInfo)
gateway.POST("/checkGatewayAliasIsExist",controller.CheckGatewayAliasIsExist)
}
ip := web.Group("/IP")
{
ip.POST("/editIPList",controller.EditIPList)
ip.POST("/getIPInfo",controller.GetIPInfo)
}
install := web.Group("/Install")
{
install.POST("/checkDBConnect",controller.CheckDBConnect)
install.POST("/checkRedisConnect",controller.CheckRedisConnect)
install.POST("/checkIsInstall",controller.CheckIsInstall)
install.POST("/installConfigure",controller.InstallConfigure)
install.POST("/install",controller.Install)
}
strategy := web.Group("/Strategy")
{
strategy.POST("/addStrategy",controller.AddStrategy)
strategy.POST("/editStrategy",controller.EditStrategy)
strategy.POST("/deleteStrategy",controller.DeleteStrategy)
strategy.POST("/getStrategyList",controller.GetStrategyList)
strategy.POST("/getSimpleStrategyList",controller.GetSimpleStrategyList)
}
auth := web.Group("/Auth")
{
auth.POST("/editAuth",controller.EditAuth)
auth.POST("/getAuthInfo",controller.GetAuthInfo)
}
rateLimit := web.Group("/RateLimit")
{
rateLimit.POST("/addRateLimit",controller.AddRateLimit)
rateLimit.POST("/editRateLimit",controller.EditRateLimit)
rateLimit.POST("/deleteRateLimit",controller.DeleteRateLimit)
rateLimit.POST("/getRateLimitInfo",controller.GetRateLimitInfo)
rateLimit.POST("/getRateLimitList",controller.GetRateLimitList)
}
}
log.Println(os.Getpid())
// router.Run(":8080")
err := endless.ListenAndServe(":8080",router)
if err != nil {
log.Println(err)
}
log.Println("Server on 8080 stopped")
os.Exit(0)
}
package main
import (
"goku-ce-1.0/conf"
"goku-ce-1.0/controller"
"goku-ce-1.0/middleware"
"fmt"
"github.com/farseer810/yawf"
)
func main() {
server := yawf.New()
server.Use(middleware.CleanupHandler)
server.Use(middleware.InjectRequestMapping)
server.Use(middleware.IPValve)
server.Use(middleware.GatewayValve)
server.Use(middleware.GatewayAuth)
server.Any(".*", controller.CreateRequest)
server.SetAddress(":" + conf.Configure["eotest_port"])
server.Listen()
fmt.Println(server.Address())
fmt.Println(server.Run())
}
#!/bin/sh
NAME=(
"gateway.go"
"monitor_redis"
)
for process in ${NAME[@]}
do
echo $process
echo "---------------"
ID=`ps -ef|grep $process|grep -v grep|grep -v PPID|awk '{print $2}'`
echo $ID
for id in $ID
do
kill -9 $id
echo "killed $id"
done
echo "---------------"
done
nohup go run gateway.go > gateway.log 2>&1 &
nohup go run monitor_redis.go > monitor_redis.log 2>&1 &
\ No newline at end of file
package middleware
import (
"goku-ce-1.0/dao/cache"
"github.com/codegangsta/inject"
"github.com/farseer810/yawf"
"log"
"net/http"
)
func CleanupHandler(context yawf.Context, log *log.Logger) {
defer func() {
if err := recover(); err != nil {
if log != nil {
log.Printf("PANIC: %s\n", err)
}
val := context.Get(inject.InterfaceOf((*http.ResponseWriter)(nil)))
res := val.Interface().(http.ResponseWriter)
res.WriteHeader(http.StatusInternalServerError)
res.Write([]byte("500 Internal Server Error"))
}
conn := cache.GetConnectionFromContext(context)
if conn != nil {
conn.Close()
}
}()
context.Next()
}
package middleware
import (
"goku-ce-1.0/dao"
"net/http"
"fmt"
"strings"
"github.com/farseer810/yawf"
)
var (
methodIndicator = map[string]string{"POST": "0", "GET": "1", "PUT": "2", "DELETE": "3", "HEAD": "4",
"OPTIONS": "5", "PATCH": "6"}
)
func isURIMatched(context yawf.Context, incomingURI, testURI string) bool {
isMatched := incomingURI == testURI
return isMatched
}
//注入请求映射
func InjectRequestMapping(httpRequest *http.Request, context yawf.Context,
httpResponse http.ResponseWriter, headers yawf.Headers) (bool, string) {
var domain, method, scheme, gatewayHashkey, requestURL string
// TODO: 0 for http, 1 for https
scheme = "0"
fmt.Println(httpRequest.RemoteAddr)
method = methodIndicator[httpRequest.Method]
if method == "" {
httpResponse.WriteHeader(404)
return false, "empty method"
}
domain = httpRequest.Host
requestURL = httpRequest.RequestURI
fmt.Println(domain)
fmt.Println(requestURL)
if len(requestURL) <= 1 {
httpResponse.WriteHeader(404)
return false, "lack url"
}
// 获取请求路径中的网关别名
requestInfo := strings.Split(requestURL,"/")
if len(requestInfo) < 3{
httpResponse.WriteHeader(404)
return false, "lack strategyKey"
}
gatewayAlias := requestInfo[1]
strategyKey := requestInfo[2]
// 通过网关别名获取网关hashKey
gatewayHashkey = dao.GetGatewayHashKey(context,gatewayAlias)
if gatewayHashkey == "" {
httpResponse.WriteHeader(404)
return false, "error gatewayAlias"
}
fmt.Println(gatewayHashkey)
paths := dao.GetAllAPIPaths(context, gatewayHashkey)
fmt.Println(paths)
var matchedURI string
gatewayLen := len(requestInfo[1]) + len(requestInfo[2]) + 2
flag := false
for _, uri := range paths {
if uri[0:4] != scheme+":"+method+":" {
continue
}
if isURIMatched(context, requestURL[gatewayLen:], uri[4:]) {
matchedURI = uri
flag = true
}
}
if !flag {
httpResponse.WriteHeader(404)
return false, "error request method!"
}
if matchedURI == "" {
httpResponse.WriteHeader(404)
return false, "url is not exist!"
}
info := dao.GetMapping(context, gatewayHashkey, matchedURI)
info.StrategyKey = strategyKey
context.Map(info)
return true, ""
}
package middleware
import (
"goku-ce-1.0/dao"
"goku-ce-1.0/utils"
"fmt"
"net/http"
"strings"
"github.com/farseer810/yawf"
"time"
)
func IPValve(httpRequest *http.Request, context yawf.Context,
httpResponse http.ResponseWriter, headers yawf.Headers) (bool, string) {
t1 := time.Now()
var info *utils.IPListInfo
var gatewayHashkey string
// 获取请求路径中的网关别名
requestInfo := strings.Split(httpRequest.RequestURI,"/")
gatewayAlias := requestInfo[1]
strategyKey := requestInfo[2]
// 通过网关别名获取网关hashKey
gatewayHashkey = dao.GetGatewayHashKey(context,gatewayAlias)
if gatewayHashkey == "" {
httpResponse.WriteHeader(404)
return false, "error gatewayAlias"
}
remoteAddr := httpRequest.RemoteAddr
remoteIP := InterceptIP(remoteAddr, ":")
info = dao.GetIPList(context, gatewayHashkey,strategyKey)
if info == nil{
return true,""
}
chooseType := info.ChooseType
if chooseType == 1 {
for _, ipList := range info.IPList {
if ipList == remoteIP {
fmt.Println(remoteIP)
httpResponse.WriteHeader(403)
return false, "illegal IP"
}
}
} else if chooseType == 2 {
for _, ipList := range info.IPList {
if ipList == remoteIP {
return true, ""
}
}
fmt.Println(remoteIP)
httpResponse.WriteHeader(403)
return false, "illegal IP"
}
fmt.Println("restrictIP time:",time.Since(t1))
return true, ""
}
func InterceptIP(str, substr string) string {
result := strings.Index(str, substr)
var rs string
if result > 7 {
rs = str[:result]
}
return rs
}
package middleware
import (
"goku-ce-1.0/dao"
"net/http"
"strings"
"time"
"fmt"
"github.com/farseer810/yawf"
"encoding/base64"
)
func GatewayAuth(httpRequest *http.Request,context yawf.Context, httpResponse http.ResponseWriter,headers yawf.Headers) (bool, string) {
var gatewayHashkey string
t1 := time.Now()
// 获取请求路径中的网关别名
requestInfo := strings.Split(httpRequest.RequestURI,"/")
gatewayAlias := requestInfo[1]
strategyKey := requestInfo[2]
// 通过网关别名获取网关hashKey
gatewayHashkey = dao.GetGatewayHashKey(context,gatewayAlias)
if gatewayHashkey == "" {
httpResponse.WriteHeader(404)
return false, "error gatewayAlias"
}
authInfo := dao.GetAuthInfo(context,gatewayHashkey,strategyKey)
if authInfo.AuthType == 0{
authStr := []byte(authInfo.UserName + ":" + authInfo.UserPassword)
authorization := "Basic " + base64.StdEncoding.EncodeToString(authStr)
fmt.Println(authorization)
fmt.Println(headers["Authorization"])
// basic鉴权
if authorization != headers["Authorization"] {
httpResponse.WriteHeader(406)
return false, "鉴权失败"
}
}else if authInfo.AuthType == 1{
// apiKey鉴权
if authInfo.ApiKey != headers["Apikey"] {
httpResponse.WriteHeader(401)
return false, "apiKey有误"
}
}
fmt.Println("auth time:",time.Since(t1))
return true,""
}
package middleware
import (
"goku-ce-1.0/dao"
"net/http"
"strings"
"time"
"fmt"
"github.com/farseer810/yawf"
)
func GatewayValve(httpRequest *http.Request,context yawf.Context, httpResponse http.ResponseWriter) (bool, string) {
t1:= time.Now()
var gatewayHashkey string
// 获取请求路径中的网关别名
requestInfo := strings.Split(httpRequest.RequestURI,"/")
gatewayAlias := requestInfo[1]
strategyKey := requestInfo[2]
// 通过网关别名获取网关hashKey
gatewayHashkey = dao.GetGatewayHashKey(context,gatewayAlias)
if gatewayHashkey == "" {
httpResponse.WriteHeader(404)
return false, "error gatewayAlias"
}
remoteAddr := httpRequest.RemoteAddr
remoteIP := InterceptIP(remoteAddr, ":")
strategySecondValve := dao.GetStrategySecondValve(context,gatewayHashkey,strategyKey)
if strategySecondValve.LimitCount != -1{
secondCount := dao.GetGatewayStrategyIPSecondCount(context,gatewayHashkey,strategyKey,remoteIP)
if secondCount >= strategySecondValve.LimitCount {
httpResponse.WriteHeader(408)
return false, "second visit limit exceeded"
}
}else if strategySecondValve.ViewType == 1 {
httpResponse.WriteHeader(408)
return false, "Don't allow visit"
}
strategyMinuteValve := dao.GetStrategyMinuteValve(context,gatewayHashkey,strategyKey)
if strategyMinuteValve.LimitCount != -1{
minuteCount := dao.GetGatewayStrategyIPMinuteCount(context,gatewayHashkey,strategyKey,remoteIP)
if minuteCount >= strategyMinuteValve.LimitCount {
httpResponse.WriteHeader(408)
return false, "minute visit limit exceeded"
}
}else if strategyMinuteValve.ViewType == 1 {
httpResponse.WriteHeader(408)
return false, "Don't allow visit"
}
strategyHourValve := dao.GetStrategyHourValve(context,gatewayHashkey,strategyKey)
fmt.Println(strategyHourValve.LimitCount)
if strategyHourValve.LimitCount != -1{
hourCount := dao.GetGatewayStrategyIPHourCount(context,gatewayHashkey,strategyKey,remoteIP)
fmt.Println(hourCount)
if hourCount >= strategyHourValve.LimitCount {
httpResponse.WriteHeader(408)
return false, "hour visit limit exceeded"
}
}else if strategyHourValve.ViewType == 1 {
httpResponse.WriteHeader(408)
return false, "Don't allow visit"
}
strategyDayValve := dao.GetStrategyDayValve(context,gatewayHashkey,strategyKey)
if strategyDayValve.LimitCount != -1{
// 获取某一时段访问次数
if strategyDayValve.StartTime != strategyDayValve.EndTime{
dayCount := dao.GetStrategyPeriodCount(context,gatewayHashkey,strategyKey,strategyDayValve.StartTime,strategyDayValve.EndTime)
fmt.Println(dayCount)
if dayCount >= strategyDayValve.LimitCount {
httpResponse.WriteHeader(408)
return false, "day visit limit exceeded"
}
}
}else if strategyDayValve.ViewType == 1 {
httpResponse.WriteHeader(408)
return false, "Don't allow visit"
}
fmt.Println("valve time:",time.Since(t1))
return true,""
}
package main
import (
"goku-ce-1.0/utils"
"goku-ce-1.0/conf"
"time"
"strconv"
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
redis "github.com/garyburd/redigo/redis"
"encoding/json"
)
var db *sql.DB
var redisConn redis.Conn
func init(){
var err error
db = getConnection()
redisConn,err = getRedisConnection()
if err != nil{
panic(err)
}
}
func main() {
dealTask()
}
func getRedisConnection() (redis.Conn, error) {
redisDB, err := strconv.Atoi(conf.Configure["redis_db"])
if err != nil {
redisDB = 0
}
if _, hasPassword := conf.Configure["redis_password"]; hasPassword {
return redis.Dial("tcp",
conf.Configure["redis_host"]+":"+conf.Configure["redis_port"],
redis.DialPassword(conf.Configure["redis_password"]),
redis.DialDatabase(redisDB))
} else {
return redis.Dial("tcp",
conf.Configure["redis_host"]+":"+conf.Configure["redis_port"],
redis.DialDatabase(redisDB))
}
}
func getConnection() *sql.DB {
var err error
var dsn string = conf.Configure["mysql_username"] + ":" + conf.Configure["mysql_password"]
dsn = dsn + "@tcp(" + conf.Configure["mysql_host"] + ":" + conf.Configure["mysql_port"] + ")/" + conf.Configure["mysql_dbname"]
dsn = dsn + "?charset=utf8"
db, err = sql.Open("mysql", dsn)
fmt.Println(dsn)
if err == nil {
if err = db.Ping();err !=nil {
panic(err)
}
db.SetMaxOpenConns(2000)
db.SetMaxIdleConns(1000)
} else {
panic(err)
}
return db
}
func dealTask(){
last := time.Now()
for {
task,err := redis.StringMap(redisConn.Do("blpop","gatewayQueue", 1))
if err != nil{
_,err = redisConn.Do("get","gatewayQueueCloseSignal")
if err !=nil {
break
}
now := time.Now()
if now.Sub(last).Minutes() >= 1{
last = now
fmt.Println(last.Format("2006-01-02 15:04:05"))
}
continue
}
time.Sleep(1000)
var taskQueue utils.QueryJson
json.Unmarshal([]byte(task["gatewayQueue"]),&taskQueue)
dataStr,err := json.Marshal(taskQueue.Data)
if err != nil{
panic(err)
}
fmt.Println(time.Now().Format("2006-01-02 15:04:05") + ":" + task["gatewayQueue"])
var data utils.OperationData
json.Unmarshal([]byte(dataStr),&data)
if taskQueue.OperationType == "gateway" {
if taskQueue.Operation == "add" {
hash_key, gateway_alias := data.GatewayHashKey, data.GatewayAlias
passAddGateway(hash_key,gateway_alias)
}else if taskQueue.Operation == "delete" {
hash_key, gateway_alias := data.GatewayHashKey, data.GatewayAlias
passDeleteGateway(hash_key,gateway_alias)
}
}else if taskQueue.OperationType == "backend" {
hash_key, gateway_id := data.GatewayHashKey, data.GatewayID
time.Sleep(1 * time.Second)
deleteApiInfo(gateway_id,hash_key)
}else if taskQueue.OperationType == "api" {
hash_key, gateway_id := data.GatewayHashKey, data.GatewayID
time.Sleep(1 * time.Second)
loadAPIList(gateway_id,hash_key)
}
}
}
func passAddGateway(hash_key,gateway_alias string) {
_,err := redisConn.Do("SET","gatewayHashKey:" + gateway_alias,hash_key)
if err != nil{
panic(err)
}
}
func passDeleteGateway(hash_key,gateway_alias string) {
redisConn.Do("apiList","apiList:" + hash_key)
redisConn.Do("del","gatewayHashKey:" + gateway_alias)
}
func deleteApiInfo(gateway_id int,hash_key string) {
keys,err := redis.Strings(redisConn.Do("keys","apiInfo:" + hash_key + "*"))
if err != nil{
panic(err)
}
if len(keys) > 0 {
fmt.Println(keys)
for _,key := range keys{
_,err = redisConn.Do("del",key)
if err != nil{
panic(err)
}
}
}
}
func loadAPIList(gateway_id int,hash_key string) {
sql := "SELECT gatewayProtocol, gatewayRequestType, gatewayRequestURI FROM eo_gateway_api WHERE gatewayID = ?"
rows,err := db.Query(sql,gateway_id)
if err != nil {
panic(err)
}
apis := make([]string,0)
defer rows.Close()
//获取记录列
for rows.Next(){
var gatewayProtocol,gatewayRequestType int
var gatewayRequestURI string
err = rows.Scan(&gatewayProtocol,&gatewayRequestType,&gatewayRequestURI)
if err != nil {
break
}
api := strconv.Itoa(gatewayProtocol) + ":" + strconv.Itoa(gatewayRequestType) + ":" + gatewayRequestURI
apis = append(apis,api)
}
listName := "apiList:" + hash_key
for _,i := range apis {
_,err := redisConn.Do("rpush",listName,i)
if err != nil{
panic(err)
}
}
fmt.Print("apis:")
fmt.Println(apis)
}
USE $mysql_dbname
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for eo_admin
-- ----------------------------
DROP TABLE IF EXISTS `eo_admin`;
CREATE TABLE `eo_admin` (
`userID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`loginCall` varchar(255) NOT NULL,
`loginPassword` varchar(255) NOT NULL,
`type` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`userID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Table structure for eo_conn_api_group_strategy
-- ----------------------------
DROP TABLE IF EXISTS `eo_conn_api_group_strategy`;
CREATE TABLE `eo_conn_api_group_strategy` (
`connID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`groupID` int(11) NOT NULL,
`strategyID` int(11) NOT NULL,
PRIMARY KEY (`connID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Table structure for eo_conn_gateway
-- ----------------------------
DROP TABLE IF EXISTS `eo_conn_gateway`;
CREATE TABLE `eo_conn_gateway` (
`connID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`userID` int(10) unsigned NOT NULL,
`gatewayID` int(10) unsigned NOT NULL,
PRIMARY KEY (`connID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for eo_gateway
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway`;
CREATE TABLE `eo_gateway` (
`gatewayID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`gatewayName` varchar(255) NOT NULL,
`gatewayDesc` varchar(200) DEFAULT NULL,
`gatewayStatus` tinyint(3) unsigned NOT NULL DEFAULT '1',
`gatewayAlias` varchar(255) NOT NULL,
`productType` tinyint(3) unsigned NOT NULL DEFAULT '0',
`endDate` datetime DEFAULT NULL,
`hashKey` varchar(255) NOT NULL,
`updateTime` datetime NOT NULL,
`createTime` datetime NOT NULL,
PRIMARY KEY (`gatewayID`,`hashKey`,`gatewayAlias`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for eo_gateway_api
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_api`;
CREATE TABLE `eo_gateway_api` (
`apiID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`apiName` varchar(255) NOT NULL,
`groupID` int(10) unsigned NOT NULL,
`gatewayProtocol` tinyint(3) unsigned NOT NULL,
`gatewayRequestType` tinyint(3) unsigned NOT NULL,
`gatewayRequestURI` varchar(255) NOT NULL,
`backendProtocol` tinyint(255) NOT NULL,
`backendRequestType` tinyint(255) NOT NULL,
`backendID` int(11) unsigned NOT NULL,
`backendRequestURI` varchar(255) NOT NULL,
`isRequestBody` tinyint(3) unsigned NOT NULL,
`gatewayRequestBodyNote` varchar(255) DEFAULT NULL,
`gatewayID` int(10) unsigned NOT NULL,
PRIMARY KEY (`apiID`,`gatewayRequestURI`,`apiName`,`gatewayID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for eo_gateway_api_cache
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_api_cache`;
CREATE TABLE `eo_gateway_api_cache` (
`cacheID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`gatewayID` int(11) unsigned NOT NULL,
`groupID` int(11) NOT NULL,
`apiID` int(11) NOT NULL,
`path` varchar(255) NOT NULL,
`apiJson` longtext NOT NULL,
`gatewayHashKey` varchar(255) NOT NULL,
`redisJson` longtext NOT NULL,
`backendID` int(11) NOT NULL,
PRIMARY KEY (`cacheID`,`path`,`gatewayID`,`gatewayHashKey`,`apiID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for eo_gateway_api_constant
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_api_constant`;
CREATE TABLE `eo_gateway_api_constant` (
`paramID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`paramKey` varchar(255) NOT NULL,
`paramValue` varchar(255) NOT NULL,
`paramName` varchar(255) DEFAULT NULL,
`backendParamPosition` tinyint(3) unsigned NOT NULL DEFAULT '0',
`apiID` int(10) unsigned NOT NULL,
PRIMARY KEY (`paramID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for eo_gateway_api_group
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_api_group`;
CREATE TABLE `eo_gateway_api_group` (
`groupID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`groupName` varchar(255) NOT NULL,
`gatewayID` int(10) unsigned NOT NULL,
`parentGroupID` int(10) unsigned NOT NULL DEFAULT '0',
`isChild` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`groupID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for eo_gateway_api_request_param
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_api_request_param`;
CREATE TABLE `eo_gateway_api_request_param` (
`paramID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`gatewayParamPostion` tinyint(3) unsigned NOT NULL DEFAULT '0',
`isNotNull` tinyint(3) unsigned NOT NULL DEFAULT '0',
`paramType` tinyint(3) unsigned NOT NULL,
`gatewayParamKey` varchar(255) NOT NULL,
`backendParamPosition` tinyint(3) unsigned NOT NULL,
`backendParamKey` varchar(255) NOT NULL,
`apiID` int(10) unsigned NOT NULL,
PRIMARY KEY (`paramID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for eo_gateway_area
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_area`;
CREATE TABLE `eo_gateway_area` (
`areaID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`areaName` varchar(255) DEFAULT NULL,
`areaStatus` tinyint(3) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`areaID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for eo_gateway_auth
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_auth`;
CREATE TABLE `eo_gateway_auth` (
`authID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`authType` tinyint(4) NOT NULL,
`apiKey` varchar(255) DEFAULT NULL,
`userName` varchar(255) DEFAULT NULL,
`userPassword` varchar(255) DEFAULT NULL,
`strategyID` int(11) NOT NULL,
PRIMARY KEY (`authID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Table structure for eo_gateway_backend
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_backend`;
CREATE TABLE `eo_gateway_backend` (
`backendID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`backendName` varchar(255) NOT NULL,
`backendURI` varchar(255) NOT NULL,
`gatewayID` int(10) unsigned NOT NULL,
PRIMARY KEY (`backendID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for eo_gateway_rate_limit
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_rate_limit`;
CREATE TABLE `eo_gateway_rate_limit` (
`limitID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`intervalType` tinyint(4) DEFAULT NULL,
`viewType` tinyint(4) NOT NULL,
`limitCount` int(11) DEFAULT NULL,
`priorityLevel` int(4) unsigned NOT NULL DEFAULT '1',
`strategyID` int(11) NOT NULL,
`createTime` timestamp NULL,
`updateTime` timestamp NULL,
`startTime` varchar(255) NOT NULL,
`endTime` varchar(255) NOT NULL,
PRIMARY KEY (`limitID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Table structure for eo_gateway_strategy_group
-- ----------------------------
DROP TABLE IF EXISTS `eo_gateway_strategy_group`;
CREATE TABLE `eo_gateway_strategy_group` (
`strategyID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`strategyName` varchar(255) NOT NULL,
`strategyKey` varchar(255) NOT NULL,
`gatewayID` int(11) NOT NULL,
`strategyDesc` varchar(255) DEFAULT NULL,
`updateTime` timestamp NULL ,
`createTime` timestamp NULL ,
`blackList` text,
`whiteList` text,
`chooseType` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`strategyID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
package controller
import (
"goku-ce-1.0/utils"
"goku-ce-1.0/server/module"
"github.com/gin-gonic/gin"
"strconv"
"encoding/json"
)
// 新增api
func AddApi(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
apiName := c.PostForm("apiName")
gatewayRequestURI := c.PostForm("gatewayRequestURI")
gatewayRequestPath := c.PostForm("gatewayRequestPath")
backendRequestURI := c.PostForm("backendURI")
backendRequestPath := c.PostForm("backendRequestPath")
gatewayRequestBodyNote := c.PostForm("gatewayRequestBodyNote")
groupID := c.PostForm("groupID")
gatewayProtocol := c.PostForm("gatewayProtocol")
gatewayRequestType := c.PostForm("gatewayRequestType")
backendProtocol := c.PostForm("backendProtocol")
backendRequestType := c.PostForm("backendRequestType")
backendID := c.PostForm("backendID")
isRequestBody := c.PostForm("isRequestBody")
gatewayRequestParam := c.PostForm("gatewayRequestParam")
constantResultParam := c.PostForm("constantResultParam")
var requestParam []utils.GatewayParam
json.Unmarshal([]byte(gatewayRequestParam),&requestParam)
var resultParam []utils.ConstantMapping
json.Unmarshal([]byte(constantResultParam),&resultParam)
gID,_:=strconv.Atoi(groupID)
gpl,_:=strconv.Atoi(gatewayProtocol)
grt,_:=strconv.Atoi(gatewayRequestType)
bpl,_:=strconv.Atoi(backendProtocol)
brt,_:=strconv.Atoi(backendRequestType)
bID,_:=strconv.Atoi(backendID)
isBody,_:=strconv.Atoi(isRequestBody)
flag,apiID := module.AddApi(gatewayHashKey,apiName,gatewayRequestURI,gatewayRequestPath,backendRequestURI,backendRequestPath,gatewayRequestBodyNote,gatewayID,gID,gpl,grt,bpl,brt,bID,isBody,requestParam,resultParam)
if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiID":apiID})
return
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}
// 修改api
func EditApi(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
apiName := c.PostForm("apiName")
gatewayRequestURI := c.PostForm("gatewayRequestURI")
gatewayRequestPath := c.PostForm("gatewayRequestPath")
backendRequestURI := c.PostForm("backendURI")
backendRequestPath := c.PostForm("backendRequestPath")
gatewayRequestBodyNote := c.PostForm("gatewayRequestBodyNote")
apiID := c.PostForm("apiID")
groupID := c.PostForm("groupID")
gatewayProtocol := c.PostForm("gatewayProtocol")
gatewayRequestType := c.PostForm("gatewayRequestType")
backendProtocol := c.PostForm("backendProtocol")
backendRequestType := c.PostForm("backendRequestType")
backendID := c.PostForm("backendID")
isRequestBody := c.PostForm("isRequestBody")
gatewayRequestParam := c.PostForm("gatewayRequestParam")
constantResultParam := c.PostForm("constantResultParam")
var requestParam []utils.GatewayParam
json.Unmarshal([]byte(gatewayRequestParam),&requestParam)
var resultParam []utils.ConstantMapping
json.Unmarshal([]byte(constantResultParam),&resultParam)
aID,_:=strconv.Atoi(apiID)
gID,_:=strconv.Atoi(groupID)
gpl,_:=strconv.Atoi(gatewayProtocol)
grt,_:=strconv.Atoi(gatewayRequestType)
bpl,_:=strconv.Atoi(backendProtocol)
brt,_:=strconv.Atoi(backendRequestType)
bID,_:=strconv.Atoi(backendID)
isBody,_:=strconv.Atoi(isRequestBody)
flag,id := module.EditApi(gatewayHashKey,apiName,gatewayRequestURI,gatewayRequestPath,backendRequestURI,backendRequestPath,gatewayRequestBodyNote,aID,gatewayID,gID,gpl,grt,bpl,brt,bID,isBody,requestParam,resultParam)
if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiID":id})
return
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}
// 彻底删除Api
func DeleteApi(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
apiID := c.PostForm("apiID")
aID,_ := strconv.Atoi(apiID)
flag := module.DeleteApi(aID,gatewayID,gatewayHashKey)
if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"api"})
return
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}
// 获取api列表并按照名称排序
func GetApiListOrderByName(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
groupID := c.PostForm("groupID")
gID,_ := strconv.Atoi(groupID)
flag,apiList := module.GetApiListOrderByName(gID)
if flag == true{
flag,gatewayInfo := module.GetSimpleGatewayInfo(gatewayHashKey)
if flag {
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiList":apiList,"gatewayInfo":gatewayInfo})
return
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}
func GetApi(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
apiID := c.PostForm("apiID")
aID,_ := strconv.Atoi(apiID)
flag,apiInfo := module.GetApi(aID)
if flag == true{
flag,gatewayInfo := module.GetSimpleGatewayInfo(gatewayHashKey)
if flag {
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiInfo":apiInfo,"gatewayInfo":gatewayInfo})
return
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
return
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}
// 获取所有API列表并依据接口名称排序
func GetAllApiListOrderByName(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
flag,apiList:= module.GetAllApiListOrderByName(gatewayID)
if flag == true{
flag,gatewayInfo := module.GetSimpleGatewayInfo(gatewayHashKey)
if flag {
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiList":apiList,"gatewayInfo":gatewayInfo})
return
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}
//搜索api
func SearchApi(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
tips := c.PostForm("tips")
flag,apiList:= module.SearchApi(tips,gatewayID)
if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiList":apiList})
return
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}
// 查重
func CheckGatewayURLIsExist(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
gatewayURL := c.PostForm("gatewayRequestPath")
flag := module.CheckGatewayURLIsExist(gatewayID,gatewayURL)
if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"api"})
return
}else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return
}
}
package controller
import (
"goku-ce-1.0/utils"
"goku-ce-1.0/server/module"
"github.com/gin-gonic/gin"
"strconv"
)
func EditAuth(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
apiKey := c.PostForm("apiKey")
userName := c.PostForm("userName")
userPassword := c.PostForm("userPassword")
authType,flag := utils.ConvertString(c.PostForm("authType"))
if !flag{
c.JSON(200,gin.H{"statusCode":"200001","type":"auth",})
return
}
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if !flag{
c.JSON(200,gin.H{"statusCode":"200002","type":"auth",})
return
}
if authType == 0{
if len(userName) < 1 {
c.JSON(200,gin.H{"type":"guest","statusCode":"200003"})
return
}else if len(userPassword)<1 || len(userPassword)>255{
c.JSON(200,gin.H{"type":"guest","statusCode":"200004"})
return
}
}
flag = module.EditAuthMethod(authType,strategyID,gatewayHashKey,apiKey,userName,userPassword)
if flag == false{
c.JSON(200,gin.H{"statusCode":"200000","type":"auth",})
return
}else{
c.JSON(200,gin.H{"type":"auth","statusCode":"000000"})
return
}
}
func GetAuthInfo(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if !flag{
c.JSON(200,gin.H{"statusCode":"200002","type":"auth",})
return
}
flag,authInfo := module.GetAuthInfo(strategyID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"200000","type":"auth",})
return
}else{
c.JSON(200,gin.H{"type":"auth","statusCode":"000000","authInfo":authInfo})
return
}
}
package controller
import (
_ "goku-ce-1.0/utils"
"goku-ce-1.0/server/module"
"github.com/gin-gonic/gin"
"strconv"
)
func AddBackend(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
backendName := c.PostForm("backendName")
backendURI := c.PostForm("backendURI")
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
flag,backendID := module.AddBackend(gatewayID,backendName,backendURI)
if flag == false{
c.JSON(200,gin.H{"statusCode":"140000","type":"gateway",})
return
}else{
c.JSON(200,gin.H{"type":"gateway","statusCode":"000000","backendID":backendID})
return
}
}
func EditBackend(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
_,gatewayID := module.GetIDFromHashKey(gatewayHashKey)
backendID := c.PostForm("backendID")
backendName := c.PostForm("backendName")
backendURI := c.PostForm("backendURI")
id,_ := strconv.Atoi(backendID)
flag := module.EditBackend(id,gatewayID,backendName,backendURI,gatewayHashKey)
if flag == false{
c.JSON(200,gin.H{"statusCode":"140000","type":"gateway",})
return
}else{
c.JSON(200,gin.H{"type":"gateway","statusCode":"000000"})
return
}
}
func DeleteBackend(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
backendID := c.PostForm("backendID")
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
id,_ := strconv.Atoi(backendID)
flag := module.DeleteBackend(gatewayID,id)
if flag == false{
c.JSON(200,gin.H{"statusCode":"140000","type":"gateway",})
return
}else{
c.JSON(200,gin.H{"type":"gateway","statusCode":"000000"})
return
}
}
func GetBackendList(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
flag,backendList := module.GetBackendList(gatewayID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"140000","type":"gateway",})
return
}else{
c.JSON(200,gin.H{"backendList":backendList,"statusCode":"000000","type":"gateway",})
return
}
}
func GetBackendInfo(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
backendID := c.PostForm("backendID")
id,_ := strconv.Atoi(backendID)
flag,backendInfo := module.GetBackendInfo(id)
if flag == false{
c.JSON(200,gin.H{"statusCode":"140000","type":"gateway",})
return
}else{
c.JSON(200,gin.H{"backendInfo":backendInfo,"statusCode":"000000","type":"gateway",})
return
}
}
package controller
import (
_ "goku-ce-1.0/utils"
"goku-ce-1.0/server/module"
"github.com/gin-gonic/gin"
"strings"
"strconv"
)
// 新增网关
func AddGateway(c *gin.Context){
var userID int
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
}
gatewayName := c.PostForm("gatewayName")
gatewayDesc := c.PostForm("gatewayDesc")
gatewayAlias := c.PostForm("gatewayAlias")
gatewayNameLen := strings.Count(gatewayName,"")-1
if gatewayNameLen<1 || gatewayNameLen > 32 {
c.JSON(200,gin.H{"type":"gateway","statusCode":"130001",})
return
}
flag,_ := module.CheckGatewayAliasIsExist(gatewayAlias)
if flag{
c.JSON(200,gin.H{"type":"gateway","statusCode":"130002",})
return
}else{
flag,gatewayHashkey := module.Addgateway(gatewayName,gatewayDesc,gatewayAlias,userID)
if flag == false {
c.JSON(200,gin.H{"type":"gateway","statusCode":"130000",})
return
}else{
c.JSON(200,gin.H{"type":"gateway","statusCode":"000000","gatewayHashKey":gatewayHashkey,})
return
}
}
}
// 修改网关
func EditGateway(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
gatewayName := c.PostForm("gatewayName")
gatewayDesc := c.PostForm("gatewayDesc")
gatewayAlias := c.PostForm("gatewayAlias")
gatewayNameLen := strings.Count(gatewayName,"")-1
if gatewayNameLen<1 || gatewayNameLen > 32 {
c.JSON(200,gin.H{"type":"gateway","statusCode":"130001",})
return
}
flag,result := module.CheckGatewayAliasIsExist(gatewayAlias)
if flag && result != gatewayHashKey{
c.JSON(200,gin.H{"type":"gateway","statusCode":"130002",})
return
}else{
flag := module.EditGateway(gatewayName,gatewayAlias,gatewayDesc,gatewayHashKey,userID)
if flag == false {
c.JSON(200,gin.H{"type":"gateway","statusCode":"130000",})
return
}else{
c.JSON(200,gin.H{"type":"gateway","statusCode":"000000"})
return
}
}
}
// 删除网关
func DeleteGateway(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
flag := module.DeleteGateway(gatewayHashKey,userID)
if flag == false {
c.JSON(200,gin.H{"type":"gateway","statusCode":"130000",})
return
}else{
c.JSON(200,gin.H{"type":"gateway","statusCode":"000000"})
return
}
}
// 获取网关信息
func GetGatewayInfo(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
flag,result := module.GetGatewayInfo(gatewayHashKey,userID)
if flag == false {
c.JSON(200,gin.H{"type":"gateway","statusCode":"130000",})
return
}else{
c.JSON(200,gin.H{"type":"gateway","statusCode":"000000","gatewayInfo":result})
return
}
}
// 获取网关列表
func GetGatewayList(c *gin.Context){
var userID int
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
}
flag,gatewayList := module.GetGatewayList(userID)
if flag == false {
c.JSON(200,gin.H{"type":"gateway","statusCode":"130000",})
return
}else{
c.JSON(200,gin.H{"type":"gateway","statusCode":"000000","gatewayList":gatewayList,})
return
}
}
// 查询网关别名是否存在
func CheckGatewayAliasIsExist(c *gin.Context) {
gatewayAlias := c.PostForm("gatewayAlias")
gatewayHashKey := c.PostForm("gatewayHashKey")
flag,result := module.CheckGatewayAliasIsExist(gatewayAlias)
if flag && result != gatewayHashKey{
c.JSON(200,gin.H{"type":"gateway","statusCode":"000000",})
return
}else{
c.JSON(200,gin.H{"type":"gateway","statusCode":"130000",})
return
}
}
package controller
import (
"goku-ce-1.0/server/module"
"github.com/gin-gonic/gin"
"strconv"
)
// 添加分组
func AddGroup(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
parentGroupID := c.DefaultPostForm("parentGroupID","0")
groupName := c.PostForm("groupName")
pID,_ := strconv.Atoi(parentGroupID)
flag,groupID := module.AddGroup(gatewayID,pID,groupName)
if flag == false{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"150000",})
return
}else{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"000000","groupID":groupID,})
return
}
}
// 删除网关api分组
func DeleteGroup(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
groupID := c.PostForm("groupID")
gID,_ := strconv.Atoi(groupID)
flag := module.DeleteGroup(gID)
if flag == false{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"150000",})
return
}else{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"000000"})
return
}
}
// 获取网关分组列表
func GetGroupList(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
flag,groupList := module.GetGroupList(gatewayID)
if flag == false{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"150000",})
return
}else{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"000000","groupList":groupList,})
return
}
}
// 修改分组信息
func EditGroup(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
groupID := c.PostForm("groupID")
parentGroupID := c.DefaultPostForm("parentGroupID","0")
groupName := c.PostForm("groupName")
gID,_ := strconv.Atoi(groupID)
pID,_ := strconv.Atoi(parentGroupID)
flag := module.EditGroup(gID,pID,groupName)
if flag == false{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"150000",})
return
}else{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"000000",})
return
}
}
// 获取分组名称
func GetGroupName(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
groupID := c.PostForm("groupID")
gID,_ := strconv.Atoi(groupID)
flag,groupName := module.GetGroupName(gID)
if flag == false{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"150000",})
return
}else{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"000000","groupName":groupName})
return
}
}
// 获取网关分组列表
func GetGroupListByKeyword(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"gateway",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
keyword := c.PostForm("keyword")
flag,groupList := module.GetGroupListByKeyword(keyword,gatewayID)
if flag == false{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"150000",})
return
}else{
c.JSON(200,gin.H{"type":"apiGroup","statusCode":"000000","groupList":groupList,})
return
}
}
package controller
import (
"goku-ce-1.0/utils"
"net/http"
"github.com/gin-gonic/gin"
"goku-ce-1.0/server/module"
"regexp"
"strconv"
)
// 用户登录
func Login(c *gin.Context){
loginCall := c.PostForm("loginCall")
loginPassword := c.PostForm("loginPassword")
if match, _ := regexp.MatchString("^[0-9a-zA-Z][0-9a-zA-Z_]{3,63}$", loginCall);match == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"120002"})
return
}else if match, _ := regexp.MatchString("^[0-9a-zA-Z]{32}$", loginPassword);match == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"120004"})
return
}else{
flag,userID,userToken := module.Login(loginCall,utils.Md5(loginPassword))
if flag == true{
userCookie := http.Cookie{Name: "userToken", Value:userToken, Path: "/", MaxAge: 86400}
userIDCookie := http.Cookie{Name: "userID", Value:strconv.Itoa(userID), Path: "/", MaxAge: 86400}
// 写入登录信息到redis
flag = module.ConfirmLoginInfo(userID,loginCall,userToken)
if flag == true{
http.SetCookie(c.Writer, &userCookie)
http.SetCookie(c.Writer, &userIDCookie)
c.JSON(200,gin.H{"type":"guest","statusCode":"000000",})
return
}else{
c.JSON(200,gin.H{"type":"guest","statusCode":"120000",})
return
}
}else{
c.JSON(200,gin.H{"type":"guest","statusCode":"120000",})
return
}
}
}
package controller
import (
"goku-ce-1.0/utils"
"goku-ce-1.0/server/module"
"github.com/gin-gonic/gin"
"strconv"
)
func EditIPList(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
ipList := c.PostForm("ipList")
chooseType,flag := utils.ConvertString(c.PostForm("chooseType"))
if !flag{
c.JSON(200,gin.H{"type":"ip","statusCode":"180001"})
return
}
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if !flag{
c.JSON(200,gin.H{"type":"ip","statusCode":"180002"})
return
}
flag = module.CheckStrategyPermission(gatewayID,strategyID)
if !flag{
c.JSON(200,gin.H{"type":"ip","statusCode":"180003"})
return
}else{
flag = module.EditIPList(strategyID,chooseType,gatewayHashKey,ipList)
if flag == true{
c.JSON(200,gin.H{"type":"ip","statusCode":"000000"})
return
}else{
c.JSON(200,gin.H{"type":"ip","statusCode":"180000"})
return
}
}
}
// 获取IP名单列表
func GetIPInfo(c *gin.Context){
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if !flag{
c.JSON(200,gin.H{"type":"ip","statusCode":"180002"})
return
}
flag = module.CheckStrategyPermission(gatewayID,strategyID)
if !flag{
c.JSON(200,gin.H{"type":"ip","statusCode":"180003"})
return
}else{
flag,ipList := module.GetIPList(strategyID)
if flag == true{
c.JSON(200,gin.H{"type":"ip","statusCode":"000000","ipInfo":ipList})
return
}else{
c.JSON(200,gin.H{"type":"ip","statusCode":"180000"})
}
}
}
package controller
import (
"goku-ce-1.0/server/module"
"github.com/gin-gonic/gin"
"goku-ce-1.0/utils"
"strings"
"regexp"
)
// 检查数据库是否可以连接
func CheckDBConnect(c *gin.Context) {
var mysql_host,mysql_port string
mysql_username := c.PostForm("mysqlUserName")
mysql_password := c.PostForm("mysqlPassword")
mysql_string := c.PostForm("mysqlHost")
mysql_dbname := c.PostForm("mysqlDBName")
mysql_array := strings.Split(mysql_string,":")
if len(mysql_array) == 2{
mysql_host = mysql_array[0]
mysql_port = mysql_array[1]
}else if len(mysql_array) == 1{
mysql_host = mysql_array[0]
mysql_port = "3306"
}
if mysql_host == ""{
c.JSON(200,gin.H{"statusCode":"200008","type":"install",})
return
}
flag := module.CheckDBConnect(mysql_username,mysql_password,mysql_host,mysql_port,mysql_dbname)
if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"install",})
return
}else{
c.JSON(200,gin.H{"statusCode":"200000","type":"install",})
return
}
}
// 检查Redis是否可以连接
func CheckRedisConnect(c *gin.Context) {
var redis_host,redis_port string
redis_db := c.PostForm("redisDB")
redis_password := c.PostForm("redisPassword")
redis_string := c.PostForm("redisHost")
redis_array := strings.Split(redis_string,":")
if len(redis_array) == 2{
redis_host = redis_array[0]
redis_port = redis_array[1]
}else if len(redis_array) == 1{
redis_host = redis_array[0]
redis_port = "6379"
}
if redis_host == ""{
c.JSON(200,gin.H{"statusCode":"200009","type":"install",})
return
}
flag := module.CheckRedisConnect(redis_db,redis_password,redis_host,redis_port)
if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"install",})
return
}else{
c.JSON(200,gin.H{"statusCode":"200000","type":"install",})
return
}
}
// 创建配置文件
func InstallConfigure(c *gin.Context) {
var mysql_host,mysql_port,redis_host,redis_port string
mysql_username := c.PostForm("mysqlUserName")
mysql_password := c.PostForm("mysqlPassword")
mysql_string := c.PostForm("mysqlHost")
mysql_dbname := c.PostForm("mysqlDBName")
mysql_array := strings.Split(mysql_string,":")
if len(mysql_array) == 2{
mysql_host = mysql_array[0]
mysql_port = mysql_array[1]
}else if len(mysql_array) == 1{
mysql_host = mysql_array[0]
mysql_port = "3306"
}
flag := module.CheckDBConnect(mysql_username,mysql_password,mysql_host,mysql_port,mysql_dbname)
if flag == true{
redis_db := c.PostForm("redisDB")
redis_password := c.PostForm("redisPassword")
redis_string := c.PostForm("redisHost")
redis_array := strings.Split(redis_string,":")
if len(redis_array) == 2{
redis_host = redis_array[0]
redis_port = redis_array[1]
}else if len(redis_array) == 1{
redis_host = redis_array[0]
redis_port = "6379"
}
flag = module.CheckRedisConnect(redis_db,redis_password,redis_host,redis_port)
if flag == true{
gatewayPort := c.PostForm("gatewayPort")
var configureInfo utils.ConfigureInfo
configureInfo.MysqlUserName = mysql_username
configureInfo.MysqlPassword = mysql_password
configureInfo.MysqlHost = mysql_host
configureInfo.MysqlPort = mysql_port
configureInfo.MysqlDBName = mysql_dbname
configureInfo.RedisDB = redis_db
configureInfo.RedisHost = redis_host
configureInfo.RedisPort = redis_port
configureInfo.RedisPassword = redis_password
configureInfo.GatewayPort = gatewayPort
configureInfo.IPMinuteVisitLimit = "100"
configureInfo.DayVisitLimit = "100000"
configureInfo.DayThroughputLimit = "104857600"
configureInfo.MinuteVisitLimit = "2000"
flag = utils.CreateConfigureFile(configureInfo)
if flag == true{
flag = utils.ReplaceDBName(mysql_dbname)
if flag{
// 安装数据库
flag = utils.InstallDB(mysql_username,mysql_password,mysql_host,mysql_port)
if flag{
// 数据库安装成功
c.JSON(200,gin.H{"statusCode":"000000","type":"install",})
utils.Stop()
return
}else{
// 数据库安装失败
c.JSON(200,gin.H{"statusCode":"200005","type":"install",})
return
}
}else{
// 替换数据库名称失败
c.JSON(200,gin.H{"statusCode":"200004","type":"install",})
return
}
}else{
// 配置文件无法创建
c.JSON(200,gin.H{"statusCode":"200003","type":"install",})
return
}
}else{
// redis数据库无法连接
c.JSON(200,gin.H{"statusCode":"200002","type":"install",})
return
}
}else{
// mysql数据库无法连接
c.JSON(200,gin.H{"statusCode":"200001","type":"install",})
return
}
}
func Install(c *gin.Context){
userName := c.PostForm("userName")
userPassword := c.PostForm("userPassword")
if match, _ := regexp.MatchString("^[0-9a-zA-Z][0-9a-zA-Z_]{3,63}$", userName);match == false{
// 用户名格式非法
c.JSON(200,gin.H{"type":"guest","statusCode":"120002"})
return
}else if match, _ := regexp.MatchString("^[0-9a-zA-Z]{32}$", userPassword);match == false{
// 用户密码格式非法
c.JSON(200,gin.H{"type":"guest","statusCode":"120004"})
return
}else{
result := module.Register(userName,utils.Md5(userPassword))
if result == true{
c.JSON(200,gin.H{"type":"guest","statusCode":"000000"})
return
}else{
// 注册失败
c.JSON(200,gin.H{"type":"guest","statusCode":"120000"})
return
}
}
}
func CheckIsInstall(c *gin.Context){
flag := utils.CheckFileIsExist("configure.json")
if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"install",})
return
}else{
c.JSON(200,gin.H{"statusCode":"200000","type":"install",})
return
}
}
package controller
import (
"github.com/gin-gonic/gin"
"goku-ce-1.0/server/module"
"strconv"
"goku-ce-1.0/utils"
"regexp"
)
// 新增流量控制
func AddRateLimit(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
viewType,flag := utils.ConvertString(c.PostForm("viewType"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210001"})
return
}
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210002"})
return
}
intervalType,flag := utils.ConvertString(c.DefaultPostForm("intervalType","0"))
if !flag && intervalType != 0{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210003"})
return
}
limitCount,flag := utils.ConvertString(c.DefaultPostForm("limitCount","0"))
if !flag && limitCount != 0{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210004"})
return
}
priorityLevel,flag := utils.ConvertString(c.PostForm("priorityLevel"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210005"})
return
}
startTime := c.PostForm("startTime")
endTime := c.PostForm("endTime")
if match, _ := regexp.MatchString(`^(20|21|22|23|[0-1]\d):[0-5]\d$`, startTime);match == false{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210006"})
return
} else if match, _ := regexp.MatchString(`^(20|21|22|23|[0-1]\d):[0-5]\d$`, endTime);match == false{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210007"})
return
} else{
flag,id:= module.AddRateLimit(viewType,strategyID,intervalType,limitCount,priorityLevel,gatewayHashKey,startTime,endTime)
if flag == true{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"000000","limitID":id})
return
}else{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210000"})
return
}
}
}
// 编辑流量控制
func EditRateLimit(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
limitID,flag := utils.ConvertString(c.PostForm("limitID"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210008"})
return
}
viewType,flag := utils.ConvertString(c.PostForm("viewType"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210001"})
return
}
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210002"})
return
}
intervalType,flag := utils.ConvertString(c.DefaultPostForm("intervalType","0"))
if !flag && intervalType != 0{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210003"})
return
}
limitCount,flag := utils.ConvertString(c.DefaultPostForm("limitCount","0"))
if !flag && limitCount != 0{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210004"})
return
}
priorityLevel,flag := utils.ConvertString(c.PostForm("priorityLevel"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210005"})
return
}
startTime := c.PostForm("startTime")
endTime := c.PostForm("endTime")
if match, _ := regexp.MatchString(`^(20|21|22|23|[0-1]\d):[0-5]\d$`, startTime);match == false{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210006"})
return
} else if match, _ := regexp.MatchString(`^(20|21|22|23|[0-1]\d):[0-5]\d$`, endTime);match == false{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210007"})
return
} else{
flag = module.EditRateLimit(strategyID,limitID,viewType,intervalType,limitCount,priorityLevel,gatewayHashKey,startTime,endTime)
if flag == true{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"000000"})
return
}else{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210000"})
return
}
}
}
// 删除流量控制
func DeleteRateLimit(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
limitID,flag := utils.ConvertString(c.PostForm("limitID"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210008"})
return
}
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210002"})
return
}
flag = module.DeleteRateLimit(strategyID,limitID,gatewayHashKey)
if flag == true{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"000000"})
return
}else{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210000"})
return
}
}
// 获取流量控制信息
func GetRateLimitInfo(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
limitID,flag := utils.ConvertString(c.PostForm("limitID"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210008"})
return
}
flag,result := module.GetRateLimitInfo(limitID)
if flag == true{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"000000","rateLimitInfo":result})
return
}else{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210000"})
return
}
}
// 获取流量控制列表
func GetRateLimitList(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if !flag{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210002"})
return
}
flag,result := module.GetRateLimitList(strategyID)
if flag == true{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"000000","rateLimitList":result})
return
}else{
c.JSON(200,gin.H{"type":"rateLimit","statusCode":"210000"})
return
}
}
\ No newline at end of file
package controller
import (
"github.com/gin-gonic/gin"
"goku-ce-1.0/server/module"
"strconv"
"goku-ce-1.0/utils"
)
// 新增策略
func AddStrategy(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
strategyName := c.PostForm("strategyName")
strategyDesc := c.PostForm("strategyDesc")
strategyNameLen := len([]rune(strategyName))
strategyDescLen := len([]rune(strategyDesc))
if strategyNameLen < 1 && strategyNameLen > 15{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190001"})
return
} else if strategyDescLen <1 && strategyDescLen > 50{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190002"})
return
} else {
flag,id,strategyKey:= module.AddStrategy(strategyName,strategyDesc,gatewayID)
if flag == true{
c.JSON(200,gin.H{"type":"strategy","statusCode":"000000","strategyID":id,"strategyKey":strategyKey})
return
}else{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190000"})
return
}
}
}
// 修改策略
func EditStrategy(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
strategyName := c.PostForm("strategyName")
strategyDesc := c.PostForm("strategyDesc")
strategyNameLen := len([]rune(strategyName))
strategyDescLen := len([]rune(strategyDesc))
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if flag == false{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190003"})
return
}else if strategyNameLen < 1 && strategyNameLen > 15{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190001"})
return
} else if strategyDescLen <1 && strategyDescLen > 50{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190002"})
return
} else {
flag = module.EditStrategy(strategyName,strategyDesc,gatewayID,strategyID)
if flag == true{
c.JSON(200,gin.H{"type":"strategy","statusCode":"000000"})
return
}else{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190000"})
return
}
}
}
// 删除策略
func DeleteStrategy(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
strategyID,flag := utils.ConvertString(c.PostForm("strategyID"))
if flag == false{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190003"})
return
} else {
flag = module.DeleteStrategy(gatewayID,strategyID)
if flag == true{
c.JSON(200,gin.H{"type":"strategy","statusCode":"000000"})
return
}else{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190000"})
return
}
}
}
// 获取策略列表
func GetStrategyList(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
flag,strategyList := module.GetStrategyList(gatewayID)
if flag == true{
c.JSON(200,gin.H{"type":"strategy","statusCode":"000000","strategyList":strategyList,})
return
}else{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190000"})
return
}
}
// 获取简易策略组列表
func GetSimpleStrategyList(c *gin.Context) {
var userID int
gatewayHashKey := c.PostForm("gatewayHashKey")
if module.CheckLogin(c) == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}else{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
flag := module.CheckGatewayPermission(gatewayHashKey,userID)
if flag == false{
c.JSON(200,gin.H{"statusCode":"100005","type":"guest",})
return
}
}
var gatewayID int
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
flag,strategyList := module.GetSimpleStrategyList(gatewayID)
if flag == true{
c.JSON(200,gin.H{"type":"strategy","statusCode":"000000","strategyList":strategyList,})
return
}else{
c.JSON(200,gin.H{"type":"strategy","statusCode":"190000"})
return
}
}
package controller
import (
"net/http"
"github.com/gin-gonic/gin"
"goku-ce-1.0/server/module"
"strconv"
"goku-ce-1.0/utils"
"regexp"
)
func Logout(c *gin.Context){
if module.CheckLogin(c) == true{
userCookie := http.Cookie{Name: "userID", Path: "/", MaxAge: -1}
http.SetCookie(c.Writer, &userCookie)
c.JSON(200,gin.H{"type":"guest","statusCode":"000000",})
}else{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
}
}
func GetUserInfo(c *gin.Context){
if module.CheckLogin(c) == true{
c.JSON(200,gin.H{"type":"guest","statusCode":"000000",})
}else{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
}
}
func EditPassword(c *gin.Context){
var userID int
if module.CheckLogin(c) == true{
result,_ := c.Request.Cookie("userID")
userID,_ = strconv.Atoi(result.Value)
}else{
c.JSON(200,gin.H{"type":"guest","statusCode":"100000",})
return
}
oldPassword := c.PostForm("oldPassword")
newPassword := c.PostForm("newPassword")
if match, _ := regexp.MatchString("^[0-9a-zA-Z]{32}$", oldPassword);match == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"120006"})
return
}else if match, _ := regexp.MatchString("^[0-9a-zA-Z]{32}$", newPassword);match == false{
c.JSON(200,gin.H{"type":"guest","statusCode":"120007"})
return
}
flag := module.EditPassword(userID,utils.Md5(oldPassword),utils.Md5(newPassword))
if flag == false{
c.JSON(200,gin.H{"statusCode":"100000","type":"guest",})
return
}else{
c.JSON(200,gin.H{"type":"guest","statusCode":"000000",})
return
}
}
func CheckLogin(c *gin.Context){
if module.CheckLogin(c) == true{
c.JSON(200,gin.H{"type":"user","statusCode":"000000",})
}else{
c.JSON(200,gin.H{"type":"user","statusCode":"100000",})
}
}
\ No newline at end of file
package dao
import (
"goku-ce-1.0/dao/database"
"goku-ce-1.0/utils"
"strconv"
"encoding/json"
)
// 新增api
func AddApi(gatewayHashKey,apiName,gatewayRequestURI,gatewayRequestPath,backendRequestURI,backendRequestPath,gatewayRequestBodyNote,apiCacheJson,redisCacheJson string,gatewayID,groupID,gatewayProtocol,gatewayRequestType,backendProtocol,backendRequestType,backendID,isRequestBody int,gatewayRequestParam []utils.GatewayParam,constantResultParam []utils.ConstantMapping) (bool,int){
db := database.GetConnection()
Tx,_ := db.Begin()
res,err := Tx.Exec("INSERT INTO eo_gateway_api (eo_gateway_api.apiName,eo_gateway_api.gatewayID,eo_gateway_api.groupID,eo_gateway_api.gatewayProtocol,eo_gateway_api.gatewayRequestType,eo_gateway_api.gatewayRequestURI,eo_gateway_api.backendProtocol,eo_gateway_api.backendRequestType,eo_gateway_api.backendID,eo_gateway_api.backendRequestURI,eo_gateway_api.isRequestBody,eo_gateway_api.gatewayRequestBodyNote) VALUES (?,?,?,?,?,?,?,?,?,?,?,?);",apiName,gatewayID,groupID,gatewayProtocol,gatewayRequestType,gatewayRequestPath,backendProtocol,backendRequestType,backendID,backendRequestURI,isRequestBody,gatewayRequestBodyNote)
if err != nil {
Tx.Rollback()
return false,0
}
if err != nil {
Tx.Rollback()
return false,0
} else{
apiID,_ := res.LastInsertId()
for i := 0;i<len(gatewayRequestParam);i++{
Tx.Exec("INSERT INTO eo_gateway_api_request_param (eo_gateway_api_request_param.apiID,eo_gateway_api_request_param.gatewayParamPostion,eo_gateway_api_request_param.isNotNull,eo_gateway_api_request_param.paramType,eo_gateway_api_request_param.gatewayParamKey,eo_gateway_api_request_param.backendParamPosition,eo_gateway_api_request_param.backendParamKey) VALUES (?,?,?,?,?,?,?);",apiID,gatewayRequestParam[i].ParamPosition,gatewayRequestParam[i].IsNotNull,gatewayRequestParam[i].ParamType,gatewayRequestParam[i].ParamKey,gatewayRequestParam[i].BackendParamPosition,gatewayRequestParam[i].BackendParamKey)
}
//插入常量参数
for i := 0;i<len(constantResultParam);i++{
Tx.Exec("INSERT INTO eo_gateway_api_constant (eo_gateway_api_constant.apiID,eo_gateway_api_constant.backendParamPosition,eo_gateway_api_constant.paramKey,eo_gateway_api_constant.paramName,eo_gateway_api_constant.paramValue) VALUES (?,?,?,?,?);",apiID,constantResultParam[i].ParamPosition,constantResultParam[i].BackendParamKey,constantResultParam[i].ParamName,constantResultParam[i].ParamValue)
}
// 写api信息进缓存表
_,err = Tx.Exec("INSERT INTO eo_gateway_api_cache (eo_gateway_api_cache.apiID,eo_gateway_api_cache.apiJson,eo_gateway_api_cache.redisJson,eo_gateway_api_cache.gatewayHashKey,eo_gateway_api_cache.gatewayID,eo_gateway_api_cache.groupID,eo_gateway_api_cache.path,eo_gateway_api_cache.backendID) VALUES (?,?,?,?,?,?,?,?);",apiID,apiCacheJson,redisCacheJson,gatewayHashKey,gatewayID,groupID,backendRequestURI,backendID)
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
if err != nil{
Tx.Rollback()
return false,0
}
var queryJson utils.QueryJson
var redisJson utils.RedisCacheJson
err = json.Unmarshal([]byte(redisCacheJson),&redisJson)
if err != nil{
Tx.Rollback()
return false,0
}
queryJson.OperationType = "api"
queryJson.Operation = "add"
queryJson.Data = redisJson
redisString,_ := json.Marshal(queryJson)
_, err = redisConn.Do("rpush", "gatewayQueue", string(redisString[:]))
if err != nil{
Tx.Rollback()
return false,0
}
Tx.Commit()
return true,int(apiID)
}
}
// 修改api
func EditApi(gatewayHashKey,apiName,gatewayRequestURI,gatewayRequestPath,backendRequestURI,backendRequestPath,gatewayRequestBodyNote,apiCacheJson,redisCacheJson string,apiID,gatewayID,groupID,gatewayProtocol,gatewayRequestType,backendProtocol,backendRequestType,backendID,isRequestBody int,gatewayRequestParam []utils.GatewayParam,constantResultParam []utils.ConstantMapping) (bool,int){
db := database.GetConnection()
Tx,_ := db.Begin()
_,err := Tx.Exec("UPDATE eo_gateway_api SET eo_gateway_api.apiName = ?,eo_gateway_api.gatewayProtocol = ?,eo_gateway_api.gatewayRequestType = ?,eo_gateway_api.gatewayRequestURI = ?,eo_gateway_api.gatewayRequestBodyNote = ?,eo_gateway_api.isRequestBody = ?,eo_gateway_api.backendID = ?,eo_gateway_api.backendProtocol = ?,eo_gateway_api.backendRequestType = ?,eo_gateway_api.backendRequestURI = ?,eo_gateway_api.groupID = ? WHERE eo_gateway_api.apiID = ? AND eo_gateway_api.gatewayID = ?;",apiName,gatewayProtocol,gatewayRequestType,gatewayRequestPath,gatewayRequestBodyNote,isRequestBody,backendID,backendProtocol,backendRequestType,backendRequestURI,groupID,apiID,gatewayID)
if err != nil {
Tx.Rollback()
return false,0
} else{
Tx.Exec("DELETE FROM eo_gateway_api_request_param WHERE eo_gateway_api_request_param.apiID = ?;",apiID)
Tx.Exec("DELETE FROM eo_gateway_api_constant WHERE eo_gateway_api_constant.apiID = ?;",apiID)
for i := 0;i<len(gatewayRequestParam);i++{
Tx.Exec("INSERT INTO eo_gateway_api_request_param (eo_gateway_api_request_param.apiID,eo_gateway_api_request_param.gatewayParamPostion,eo_gateway_api_request_param.isNotNull,eo_gateway_api_request_param.paramType,eo_gateway_api_request_param.gatewayParamKey,eo_gateway_api_request_param.backendParamPosition,eo_gateway_api_request_param.backendParamKey) VALUES (?,?,?,?,?,?,?);",apiID,gatewayRequestParam[i].ParamPosition,gatewayRequestParam[i].IsNotNull,gatewayRequestParam[i].ParamType,gatewayRequestParam[i].ParamKey,gatewayRequestParam[i].BackendParamPosition,gatewayRequestParam[i].BackendParamKey)
}
//插入常量参数
for i := 0;i<len(constantResultParam);i++{
Tx.Exec("INSERT INTO eo_gateway_api_constant (eo_gateway_api_constant.apiID,eo_gateway_api_constant.backendParamPosition,eo_gateway_api_constant.paramKey,eo_gateway_api_constant.paramName,eo_gateway_api_constant.paramValue) VALUES (?,?,?,?,?);",apiID,constantResultParam[i].ParamPosition,constantResultParam[i].BackendParamKey,constantResultParam[i].ParamName,constantResultParam[i].ParamValue)
}
// 写api信息进缓存表
Tx.Exec("UPDATE eo_gateway_api_cache SET eo_gateway_api_cache.groupID = ?,eo_gateway_api_cache.path = ?,eo_gateway_api_cache.backendID = ?,eo_gateway_api_cache.apiJson = ?,eo_gateway_api_cache.redisJson = ? WHERE eo_gateway_api_cache.apiID = ? AND eo_gateway_api_cache.gatewayID = ?;",groupID,backendRequestURI,backendID,apiCacheJson,redisCacheJson,apiID,gatewayID)
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
if err != nil{
Tx.Rollback()
return false,0
}
flag,gatewayKey := getRedisApi(apiID)
if flag == false{
Tx.Rollback()
return false,0
}
var queryJson utils.QueryJson
var redisJson utils.RedisCacheJson
err = json.Unmarshal([]byte(redisCacheJson),&redisJson)
if err != nil{
Tx.Rollback()
return false,0
}
queryJson.OperationType = "api"
queryJson.Operation = "update"
queryJson.Data = redisJson
redisString,_ := json.Marshal(queryJson)
_, err = redisConn.Do("DEL", "apiInfo:" + gatewayHashKey + ":" + gatewayKey)
if err != nil{
Tx.Rollback()
return false,0
}
_, err = redisConn.Do("rpush", "gatewayQueue",string(redisString[:]))
if err != nil{
Tx.Rollback()
return false,0
}
Tx.Commit()
return true,int(apiID)
}
}
// 彻底删除Api
func DeleteApi(apiID,gatewayID int,gatewayHashKey string) bool{
db := database.GetConnection()
Tx,_ := db.Begin()
//删除基础信息
stmt,_ := Tx.Prepare("DELETE FROM eo_gateway_api WHERE eo_gateway_api.apiID = ?")
stmt.Exec(apiID)
//删除缓存信息
stmt,_ = Tx.Prepare("DELETE FROM eo_gateway_api_cache WHERE eo_gateway_api_cache.apiID = ?;")
stmt.Exec(apiID)
//删除请求参数
stmt,_ = Tx.Prepare("DELETE FROM eo_gateway_api_request_param WHERE eo_gateway_api_request_param.apiID = ?;")
stmt.Exec(apiID)
//删除常量参数
stmt,_ = Tx.Prepare("DELETE FROM eo_gateway_api_constant WHERE eo_gateway_api_constant.apiID = ?;")
stmt.Exec(apiID)
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
if err != nil{
Tx.Rollback()
return false
}
var operationData utils.OperationData
operationData.ApiID = apiID
operationData.GatewayID = gatewayID
operationData.GatewayHashKey = gatewayHashKey
var queryJson utils.QueryJson
queryJson.OperationType = "api"
queryJson.Operation = "delete"
queryJson.Data = operationData
redisString,_ := json.Marshal(queryJson)
_, err = redisConn.Do("rpush", "gatewayQueue",string(redisString[:]))
if err != nil{
Tx.Rollback()
return false
}
Tx.Commit()
return true
}
// 获取api列表并按照名称排序
func GetApiListOrderByName(groupID int) (bool,[]*utils.ApiInfo){
db := database.GetConnection()
// 获取多级分组列表
rows,err := db.Query(`SELECT eo_gateway_api_group.groupID FROM eo_gateway_api_group WHERE eo_gateway_api_group.parentGroupID = ?;`,groupID)
groupSql := "" + strconv.Itoa(groupID)
defer rows.Close()
//如果存在子分组,则拼接搜索的范围
for rows.Next(){
var childGroupID int
rows.Scan(&childGroupID)
groupSql += "," + strconv.Itoa(childGroupID)
}
rows,err = db.Query(`SELECT eo_gateway_api.apiID,eo_gateway_api.apiName,eo_gateway_api.groupID,eo_gateway_api.gatewayProtocol,eo_gateway_api.gatewayRequestType,eo_gateway_api.gatewayRequestURI FROM eo_gateway_api WHERE eo_gateway_api.groupID IN (?) ORDER BY eo_gateway_api.apiID DESC;`,groupSql)
apiList := make([]*utils.ApiInfo,0)
flag := true
num :=0
//延时关闭Rows
defer rows.Close()
//获取记录列
if _, err = rows.Columns(); err != nil {
return false,apiList
} else {
for rows.Next(){
var apiInfo utils.ApiInfo
err = rows.Scan(&apiInfo.ApiID,&apiInfo.ApiName,&apiInfo.GroupID,&apiInfo.GatewayProtocol,&apiInfo.GatewayRequestType,&apiInfo.GatewayRequestURI)
if err != nil{
flag = false
break
}
apiList = append(apiList,&apiInfo)
num +=1
}
}
if num == 0{
flag =false
}
return flag,apiList
}
func GetApi(apiID int) (bool,utils.ApiInfo){
db := database.GetConnection()
var apiJson string
var apiInfo utils.ApiInfo
sql := "SELECT eo_gateway_api_cache.apiID,eo_gateway_api_cache.groupID,eo_gateway_api_cache.apiJson,eo_gateway_api_group.parentGroupID FROM eo_gateway_api_cache INNER JOIN eo_gateway_api_group ON eo_gateway_api_cache.groupID = eo_gateway_api_group.groupID WHERE eo_gateway_api_cache.apiID = ?;"
err := db.QueryRow(sql,apiID).Scan(&apiInfo.ApiID,&apiInfo.GroupID,&apiJson,&apiInfo.ParentGroupID)
if err != nil{
return false,apiInfo
}else{
json.Unmarshal([]byte(apiJson),&apiInfo.ApiJson)
return true,apiInfo
}
}
// 获取所有API列表并依据接口名称排序
func GetAllApiListOrderByName(gatewayID int) (bool,[]*utils.ApiInfo){
db := database.GetConnection()
rows,err :=db.Query(`SELECT eo_gateway_api.apiID,eo_gateway_api.apiName,eo_gateway_api.groupID,eo_gateway_api.gatewayProtocol,eo_gateway_api.gatewayRequestType,eo_gateway_api.gatewayRequestURI FROM eo_gateway_api WHERE eo_gateway_api.gatewayID = ?;`,gatewayID)
apiList := make([]*utils.ApiInfo,0)
flag := true
num :=0
//延时关闭Rows
defer rows.Close()
//获取记录列
if _, err = rows.Columns(); err != nil {
return false,apiList
} else {
for rows.Next(){
var apiInfo utils.ApiInfo
err = rows.Scan(&apiInfo.ApiID,&apiInfo.ApiName,&apiInfo.GroupID,&apiInfo.GatewayProtocol,&apiInfo.GatewayRequestType,&apiInfo.GatewayRequestURI)
if err != nil{
flag = false
break
}
apiList = append(apiList,&apiInfo)
num +=1
}
}
if num == 0{
flag =false
}
return flag,apiList
}
//搜索api
func SearchApi(tips string,gatewayID int) (bool,[]*utils.ApiInfo){
db := database.GetConnection()
rows,err :=db.Query(`SELECT eo_gateway_api.apiID,eo_gateway_api.apiName,eo_gateway_api.groupID,eo_gateway_api.gatewayProtocol,eo_gateway_api.gatewayRequestType,eo_gateway_api.gatewayRequestURI FROM eo_gateway_api WHERE eo_gateway_api.gatewayID = ? AND (eo_gateway_api.apiName LIKE ? OR eo_gateway_api.gatewayRequestURI LIKE ?) ORDER BY eo_gateway_api.apiName;`,gatewayID,"%" + tips + "%","%" + tips + "%")
apiList := make([]*utils.ApiInfo,0)
flag := true
num :=0
for rows.Next(){
var apiInfo utils.ApiInfo
err = rows.Scan(&apiInfo.ApiID,&apiInfo.ApiName,&apiInfo.GroupID,&apiInfo.GatewayProtocol,&apiInfo.GatewayRequestType,&apiInfo.GatewayRequestURI)
if err != nil{
flag = false
break
}
apiList = append(apiList,&apiInfo)
num +=1
}
if num == 0{
flag =false
}
return flag,apiList
}
// 获取网关接口信息,方便更新网关服务器的Redis数据
func GetRedisApiList(gatewayID int) (bool,[]*utils.ApiInfo){
db := database.GetConnection()
rows,err :=db.Query(`SELECT eo_gateway_api.gatewayProtocol,eo_gateway_api.gatewayRequestType,eo_gateway_api.gatewayRequestURI FROM eo_gateway_api WHERE eo_gateway_api.gatewayID = ?;`,gatewayID)
apiList := make([]*utils.ApiInfo,0)
flag := true
num :=0
//延时关闭Rows
defer rows.Close()
//获取记录列
if _, err = rows.Columns(); err != nil {
return false,apiList
} else {
for rows.Next(){
var apiInfo utils.ApiInfo
err = rows.Scan(&apiInfo.GatewayProtocol,&apiInfo.GatewayRequestType,&apiInfo.GatewayRequestURI)
if err != nil{
flag = false
break
}
apiList = append(apiList,&apiInfo)
num +=1
}
}
if num == 0{
flag =false
}
return flag,apiList
}
// 获取接口的核心信息
func GetRedisApi(apiID int) (bool,utils.ApiInfo){
db := database.GetConnection()
var apiInfo utils.ApiInfo
sql := "SELECT eo_gateway_api.gatewayProtocol,eo_gateway_api.gatewayRequestType,eo_gateway_api.gatewayRequestURI FROM eo_gateway_api WHERE eo_gateway_api.apiID = ?;"
err := db.QueryRow(sql,apiID).Scan(&apiInfo.GatewayProtocol,&apiInfo.GatewayRequestType,&apiInfo.GatewayRequestURI)
if err != nil{
return false,apiInfo
}else{
return true,apiInfo
}
}
// 查重
func CheckGatewayURLIsExist(gatewayID int,gatewayURI string) (bool,int){
db := database.GetConnection()
var apiID int
sql := "SELECT apiID FROM eo_gateway_api WHERE gatewayID = ? AND gatewayRequestURI = ?;"
err := db.QueryRow(sql,gatewayID,gatewayURI).Scan(&apiID)
if err != nil{
return false,apiID
}else{
return true,apiID
}
}
func getRedisApi(apiID int) (bool,string){
db := database.GetConnection()
var gatewayProtocol,gatewayRequestType,gatewayRequestURI string
sql := "SELECT eo_gateway_api.gatewayProtocol,eo_gateway_api.gatewayRequestType,eo_gateway_api.gatewayRequestURI FROM eo_gateway_api WHERE eo_gateway_api.apiID = ?;"
err := db.QueryRow(sql,apiID).Scan(&gatewayProtocol,&gatewayRequestType,&gatewayRequestURI)
if err != nil{
return false,""
}else{
return true,gatewayProtocol+":"+gatewayRequestType+":"+gatewayRequestURI
}
}
// /**
// * 获取接口的核心信息
// */
// public function getRedisApi(&$api_id)
// {
// $db = getDatabase();
// $result = $db -> prepareExecute('SELECT eo_gateway_api.gatewayProtocol,eo_gateway_api.gatewayRequestType,eo_gateway_api.gatewayRequestURI FROM eo_gateway_api WHERE eo_gateway_api.apiID = ?;', array($api_id));
// if (empty($result))
// return FALSE;
// else
// return $result['gatewayProtocol'] . ':' . $result['gatewayRequestType'] . ':' . $result['gatewayRequestURI'];
// }
package dao
import (
"goku-ce-1.0/dao/database"
"goku-ce-1.0/utils"
)
func AddAuthMethod(authType,strategyID int,apiKey,userName,userPassword string) bool{
db := database.GetConnection()
sql := "INSERT INTO eo_gateway_auth (authType,strategyID,apiKey,userName,userPassword) VALUES(?,?,?,?,?);"
stmt,err := db.Prepare(sql)
if err != nil{
return false
}
defer stmt.Close()
_,err = stmt.Exec(authType,strategyID,apiKey,userName,userPassword)
if err != nil{
return false
}else{
return true
}
}
func EditAuthMethod(authType,strategyID int,gatewayHashKey,apiKey,userName,userPassword string) bool{
db := database.GetConnection()
sql := "UPDATE eo_gateway_auth SET authType = ?,apiKey = ?,userName = ?,userPassword = ? WHERE strategyID = ?;"
stmt,err := db.Prepare(sql)
if err != nil{
return false
}
defer stmt.Close()
_,err = stmt.Exec(authType,apiKey,userName,userPassword,strategyID)
if err != nil{
return false
}else{
var strategyKey string
err = db.QueryRow("SELECT strategyKey FROM eo_gateway_strategy_group WHERE strategyID = ?;",strategyID).Scan(&strategyKey)
if err != nil{
return false
}
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
_, err = redisConn.Do("del", "authInfo:"+ gatewayHashKey + ":" + strategyKey)
if err != nil{
return false
}
return true
}
}
func DeleteAuth(strategyID int) (bool){
db := database.GetConnection()
sql := "DELETE FROM eo_gateway_auth WHERE strategyID = ?;"
stmt,err := db.Prepare(sql)
if err != nil{
return false
}
defer stmt.Close()
res,err := stmt.Exec(strategyID)
if err != nil{
return false
}else{
if rowAffect,_:=res.RowsAffected(); rowAffect > 0{
return true
}else{
return false
}
}
}
func GetAuthInfo(strategyID int) (bool,utils.AuthInfo){
db := database.GetConnection()
var authInfo utils.AuthInfo
sql := "SELECT authType,apiKey,userName,userPassword FROM eo_gateway_auth WHERE strategyID = ?;"
err := db.QueryRow(sql,strategyID).Scan(&authInfo.AuthType,&authInfo.ApiKey,&authInfo.UserName,&authInfo.UserPassword)
if err != nil{
return false,authInfo
}else{
return true,authInfo
}
}
func CheckAuthIsExist(strategyID int) (bool){
db := database.GetConnection()
sql := "SELECT strategyID FROM eo_gateway_auth WHERE strategyID = ?;"
err := db.QueryRow(sql,strategyID).Scan(&strategyID)
if err != nil{
return false
}else{
return true
}
}
package dao
import (
"goku-ce-1.0/dao/database"
"goku-ce-1.0/utils"
"encoding/json"
)
// 获取环境列表
func GetBackendList(gatewayID int) (bool,[]*utils.BackendInfo){
db := database.GetConnection()
rows,err := db.Query(`SELECT eo_gateway_backend.backendID,eo_gateway_backend.backendName,eo_gateway_backend.backendURI FROM eo_gateway_backend WHERE eo_gateway_backend.gatewayID = ? ORDER BY eo_gateway_backend.backendID DESC;`,gatewayID)
backendList := make([]*utils.BackendInfo,0)
flag := true
if err != nil {
flag = false
}
num :=0
//延时关闭Rows
defer rows.Close()
//获取记录列
if _, err = rows.Columns(); err != nil {
return false,backendList
} else {
for rows.Next(){
var backend utils.BackendInfo
err:= rows.Scan(&backend.BackendID,&backend.BackendName,&backend.BackendURI)
if err!=nil{
flag = false
break
}
backendList = append(backendList,&backend)
num +=1
}
}
if num == 0{
flag =false
}
return flag,backendList
}
// 添加环境
func AddBackend(gatewayID int,backendName ,backendURI string) (bool,int){
db := database.GetConnection()
stmt,err := db.Prepare(`INSERT INTO eo_gateway_backend (eo_gateway_backend.backendName,eo_gateway_backend.backendURI,eo_gateway_backend.gatewayID) VALUES (?,?,?);`)
defer stmt.Close()
if err != nil {
return false,0
}
res, err := stmt.Exec(backendName,backendURI,gatewayID)
if err != nil {
return false,0
} else{
id, _ := res.LastInsertId()
return true,int(id)
}
}
func DeleteBackend(gatewayID,backendID int) bool{
db := database.GetConnection()
stmt,err := db.Prepare(`DELETE FROM eo_gateway_backend WHERE eo_gateway_backend.backendID = ? AND eo_gateway_backend.gatewayID = ?;`)
defer stmt.Close()
if err != nil {
return false
}
res, err := stmt.Exec(backendID,gatewayID)
if err != nil {
return false
} else{
if rowAffect,_:=res.RowsAffected(); rowAffect > 0{
return true
}else{
return false
}
}
}
func EditBackend(backendID,gatewayID int,backendName,backendURI,gatewayHashKey string) bool{
db := database.GetConnection()
Tx,_ := db.Begin()
stmt,err := Tx.Prepare(`UPDATE eo_gateway_backend SET eo_gateway_backend.backendName = ?,eo_gateway_backend.backendURI = ? WHERE eo_gateway_backend.backendID = ?;`)
if err != nil {
Tx.Rollback()
return false
}
_, err = stmt.Exec(backendName,backendURI,backendID)
if err != nil {
Tx.Rollback()
return false
} else{
Tx.Exec("UPDATE eo_gateway_api SET backendURI = ? WHERE backendID = ?",backendURI,backendID)
Tx.Exec("UPDATE eo_gateway_api_cache SET path = ? WHERE backendID = ?",backendURI,backendID)
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
if err != nil{
Tx.Rollback()
return false
}
var queryJson utils.QueryJson
var operationData utils.OperationData
operationData.GatewayID = gatewayID
operationData.GatewayHashKey = gatewayHashKey
queryJson.OperationType = "backend"
queryJson.Operation = "update"
queryJson.Data = operationData
redisString,_ := json.Marshal(queryJson)
_, err = redisConn.Do("rpush", "gatewayQueue", string(redisString[:]))
if err != nil{
Tx.Rollback()
return false
}
Tx.Commit()
return true
}
}
// 获取网关信息
func GetBackendInfo(backendID int) (bool,utils.BackendInfo){
db := database.GetConnection()
var backendInfo utils.BackendInfo
err := db.QueryRow("SELECT eo_gateway_backend.backendID,eo_gateway_backend.backendName,eo_gateway_backend.backendURI FROM eo_gateway_backend WHERE eo_gateway_backend.backendID = ?;",backendID).Scan(&backendInfo.BackendID,&backendInfo.BackendName,&backendInfo.BackendURI)
if err != nil {
return false,backendInfo
} else{
return true,backendInfo
}
}
\ No newline at end of file
package dao
import (
"goku-ce-1.0/dao/database"
"goku-ce-1.0/utils"
"encoding/json"
"time"
"strconv"
"github.com/garyburd/redigo/redis"
"goku-ce-1.0/conf"
)
// 新增网关
func Addgateway(gatewayName,gatewayDesc,gatewayAlias,createTime,hashKey string,userID int) (bool,int){
db := database.GetConnection()
Tx,_ :=db.Begin()
stmt,err := Tx.Prepare(`INSERT INTO eo_gateway (eo_gateway.gatewayName,eo_gateway.gatewayDesc,eo_gateway.gatewayAlias,eo_gateway.hashKey,eo_gateway.createTime,eo_gateway.updateTime) VALUES (?,?,?,?,?,?);`)
if err != nil {
Tx.Rollback()
return false,0
}
defer stmt.Close()
res, err := stmt.Exec(gatewayName, gatewayDesc,gatewayAlias,hashKey,createTime,createTime)
if err != nil {
Tx.Rollback()
return false,0
} else{
id, _ := res.LastInsertId()
stmt ,err = Tx.Prepare("INSERT INTO eo_conn_gateway (eo_conn_gateway.gatewayID,eo_conn_gateway.userID) VALUES (?,?);")
if err != nil {
Tx.Rollback()
return false,0
}
_,err = stmt.Exec(int(id),userID)
if err != nil {
Tx.Rollback()
return false,0
}
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
var queryJson utils.QueryJson
var operationData utils.OperationData
operationData.GatewayAlias = gatewayAlias
operationData.GatewayID = int(id)
operationData.GatewayHashKey = hashKey
queryJson.OperationType = "gateway"
queryJson.Operation = "add"
queryJson.Data = operationData
redisString,_ := json.Marshal(queryJson)
_, err = redisConn.Do("rpush", "gatewayQueue", string(redisString[:]))
if err != nil{
Tx.Rollback()
return false,0
}
Tx.Commit()
return true,int(id)
}
}
// 修改网关
func EditGateway(gatewayName,gatewayAlias,gatewayDesc,gatewayHashKey string) bool{
db := database.GetConnection()
flag,oldAlias := GetGatewayAlias(gatewayHashKey)
if flag{
stmt,err := db.Prepare(`UPDATE eo_gateway SET gatewayName = ?,gatewayAlias = ?,gatewayDesc = ? WHERE hashKey = ?;`)
defer stmt.Close()
if err != nil {
return false
}
_,err = stmt.Exec(gatewayName,gatewayAlias,gatewayDesc,gatewayHashKey)
if err != nil {
return false
} else{
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
var queryJson utils.QueryJson
var operationData utils.OperationData
operationData.GatewayHashKey = gatewayHashKey
operationData.GatewayAlias = oldAlias
queryJson.OperationType = "gateway"
queryJson.Operation = "delete"
queryJson.Data = operationData
redisString,_ := json.Marshal(queryJson)
_, err = redisConn.Do("rpush", "gatewayQueue", string(redisString[:]))
if err != nil{
return false
}
return true
}
}else{
return false
}
}
// 删除网关
func DeleteGateway(gatewayHashkey string) bool{
db := database.GetConnection()
flag,id :=GetIDFromHashKey(gatewayHashkey)
if flag{
flag,gatewayAlias := GetGatewayAlias(gatewayHashkey)
if flag{
stmt,err := db.Prepare(`DELETE FROM eo_gateway WHERE hashKey = ?;`)
defer stmt.Close()
if err != nil {
return false
}
_,err = stmt.Exec(gatewayHashkey)
if err != nil {
return false
} else{
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
var queryJson utils.QueryJson
var operationData utils.OperationData
operationData.GatewayID = int(id)
operationData.GatewayHashKey = gatewayHashkey
operationData.GatewayAlias = gatewayAlias
queryJson.OperationType = "gateway"
queryJson.Operation = "delete"
queryJson.Data = operationData
redisString,_ := json.Marshal(queryJson)
_, err = redisConn.Do("rpush", "gatewayQueue", string(redisString[:]))
if err != nil{
return false
}
return true
}
}else{
return false
}
}else{
return false
}
}
// 从hashKey获取ID
func GetIDFromHashKey(gatewayHashKey string) (bool,int){
db := database.GetConnection()
gatewayID := 0
sql := `SELECT eo_gateway.gatewayID FROM eo_gateway WHERE eo_gateway.hashKey = ?;`
err := db.QueryRow(sql,gatewayHashKey).Scan(&gatewayID)
flag := true
if err != nil{
flag = false
}
return flag,gatewayID
}
/**
* 判断网关和用户是否匹配
* @param $gateway_id 网关数字ID
* @param $user_id 用户数字ID
*/
func CheckGatewayPermission(gatewayID ,userID int) bool{
db :=database.GetConnection()
sql := `SELECT eo_conn_gateway.gatewayID FROM eo_conn_gateway WHERE eo_conn_gateway.gatewayID = ? AND eo_conn_gateway.userID = ?;`
err := db.QueryRow(sql,gatewayID,userID).Scan(&gatewayID)
if err != nil{
return true
}else{
return true
}
}
// 获取网关列表
func GetGatewayList(userID int) (bool,[]*utils.GatewayInfo){
db := database.GetConnection()
var err error
rows,err := db.Query(`SELECT eo_gateway.gatewayID,eo_gateway.gatewayName,eo_gateway.gatewayAlias,eo_gateway.gatewayStatus,eo_gateway.productType,eo_gateway.gatewayDesc,eo_gateway.updateTime,eo_gateway.hashKey AS gatewayHashKey FROM eo_gateway INNER JOIN eo_conn_gateway ON eo_gateway.gatewayID = eo_conn_gateway.gatewayID WHERE eo_conn_gateway.userID = ?;`,userID)
gatewayList := make([]*utils.GatewayInfo,0)
flag := true
if err != nil {
flag = false
}
num :=0
//延时关闭Rows
defer rows.Close()
//获取记录列
if _, err = rows.Columns(); err != nil {
return false,gatewayList
} else {
for rows.Next(){
var gateway utils.GatewayInfo
err = rows.Scan(&gateway.GatewayID,&gateway.GatewayName,&gateway.GatewayAlias,&gateway.GatewayStatus,&gateway.ProductType,&gateway.GatewayDesc,&gateway.UpdateTime,&gateway.GatewayHashKey);
if err!=nil{
flag = false
break
}
gatewayList = append(gatewayList,&gateway)
num +=1
}
}
if num == 0{
flag =false
}
return flag,gatewayList
}
// 获取网关信息
func GetGatewayInfo(gatewayHashKey string) (bool,map[string]interface{}){
db := database.GetConnection()
var gatewayID int
var gatewayName,gatewayDesc,gatewayStatus,updateTime,createTime,gatewayAlias string
sql := `SELECT eo_gateway.gatewayID,eo_gateway.gatewayName,eo_gateway.gatewayDesc,eo_gateway.gatewayStatus,eo_gateway.updateTime,eo_gateway.createTime,eo_gateway.gatewayAlias FROM eo_gateway WHERE eo_gateway.hashKey = ?;`
err := db.QueryRow(sql,gatewayHashKey).Scan(&gatewayID,&gatewayName,&gatewayDesc,&gatewayStatus,&updateTime,&createTime,&gatewayAlias)
if err != nil{
return false,nil
}
redisInfo := GetGatewayInfoByRedis(gatewayHashKey)
now := time.Now()
ct,err := time.ParseInLocation("2006-01-02 15:04:05",createTime,time.Local)
if err != nil{
return false,nil
}
subTime := now.Sub(ct)
minute := int(subTime.Minutes())%60
hour := int(subTime.Hours())%24
day := int(subTime.Hours())/24
monitorTime := strconv.Itoa(day) + " 天" + strconv.Itoa(hour) + " 时" + strconv.Itoa(minute) + " 分"
gatewayPort := conf.Configure["eotest_port"]
// 获取策略组数量
apiGroupCount := GetApiGroupCount(gatewayHashKey)
strategyGroupCount := GetStrategyCount(gatewayHashKey)
return true,map[string]interface{}{"gatewayID":gatewayID,"gatewayName":gatewayName,"gatewayDesc":gatewayDesc,"gatewayStatus":gatewayStatus,"updateTime":updateTime,"createTime":createTime,"gatewayAlias":gatewayAlias,"gatewayPort":gatewayPort,"monitorTime":monitorTime,"apiGroupCount":apiGroupCount,"strategyGroupCount":strategyGroupCount,"redisInfo":redisInfo}
}
// 通过hashKey获取网关别名
func GetGatewayAlias(gatewayHashKey string) (bool,string){
db := database.GetConnection()
var gatewayAlias string
sql := "SELECT gatewayAlias FROM eo_gateway WHERE hashKey = ?;"
err := db.QueryRow(sql,gatewayHashKey).Scan(&gatewayAlias)
if err != nil{
return false,""
}else{
return true,gatewayAlias
}
}
// 查询网关别名是否存在
func CheckGatewayAliasIsExist(gatewayAlias string) (bool,string){
db := database.GetConnection()
var hashKey string
sql := "SELECT gatewayHashkey FROM eo_gateway WHERE gatewayAlias = ?;"
err := db.QueryRow(sql,gatewayAlias).Scan(&hashKey)
if err != nil{
return false,""
}else{
return true,hashKey
}
}
// 获取网关访问实时信息
func GetGatewayInfoByRedis(gatewayHashKey string) interface{}{
now := time.Now()
year, month, day := now.Date()
dateStr := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
hour := now.Hour()
minute := now.Minute()
second := now.Second()
timeStr := dateStr + "-" + strconv.Itoa(hour) + "-" + strconv.Itoa(minute)
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
redisKey := "gatewayMinuteCount:" + gatewayHashKey + ":" + timeStr
gatewayMinuteCount, err := redis.String(redisConn.Do("GET",redisKey))
if err != nil {
gatewayMinuteCount = "0"
}
redisKey = "gatewayDayCount:" + gatewayHashKey+ ":" + dateStr
gatewayDayCount, err := redis.String(redisConn.Do("GET",redisKey))
if err != nil {
gatewayDayCount = "0"
}
redisKey = "gatewaySuccessCount:" + gatewayHashKey + ":" + dateStr
gatewaySuccessCount, err := redis.String(redisConn.Do("GET",redisKey))
if err != nil {
gatewaySuccessCount = "0"
}
redisKey = "gatewayFailureCount:" + gatewayHashKey + ":" + dateStr
gatewayFailureCount, err := redis.String(redisConn.Do("GET",redisKey))
if err != nil {
gatewayFailureCount = "0"
}
hourStr := ""
if hour < 10 {
hourStr += "0"
}
minuteStr := ""
if minute < 10{
minuteStr += "0"
}
secondStr := ""
if second<10{
secondStr += "0"
}
lastUpdateTime := hourStr + strconv.Itoa(hour) + ":" + minuteStr + strconv.Itoa(minute) + ":" + secondStr + strconv.Itoa(second)
return map[string]interface{}{"gatewayMinuteCount":gatewayMinuteCount,"gatewayDayCount":gatewayDayCount,"gatewaySuccessCount":gatewaySuccessCount,"gatewayFailureCount":gatewayFailureCount,"lastUpdateTime":lastUpdateTime}
}
// 获取简易网关信息
func GetSimpleGatewayInfo(gatewayHashKey string) (bool,interface{}) {
db := database.GetConnection()
var gatewayID int
var gatewayName,gatewayAlias string
sql := `SELECT eo_gateway.gatewayID,eo_gateway.gatewayName,eo_gateway.gatewayAlias FROM eo_gateway WHERE eo_gateway.hashKey = ?;`
err := db.QueryRow(sql,gatewayHashKey).Scan(&gatewayID,&gatewayName,&gatewayAlias)
if err != nil{
return false,nil
}
gatewayPort := conf.Configure["eotest_port"]
return true,map[string]interface{}{"gatewayID":gatewayID,"gatewayName":gatewayName,"gatewayAlias":gatewayAlias,"gatewayPort":gatewayPort}
}
\ No newline at end of file
package dao
import (
"goku-ce-1.0/dao/database"
"goku-ce-1.0/utils"
)
// 添加分组
func AddGroup(gatewayID int,groupName string) (bool,int){
db := database.GetConnection()
stmt,err := db.Prepare(`INSERT INTO eo_gateway_api_group (eo_gateway_api_group.groupName,eo_gateway_api_group.gatewayID) VALUES (?,?);`)
defer stmt.Close()
if err != nil {
return false,0
}
res, err := stmt.Exec(groupName,gatewayID)
if err != nil {
return false,0
} else{
id, _ := res.LastInsertId()
return true,int(id)
}
}
// 添加子分组
func AddChildGroup(gatewayID ,parentGroupID int,groupName string) (bool,int){
db := database.GetConnection()
stmt,err := db.Prepare(`INSERT INTO eo_gateway_api_group (eo_gateway_api_group.groupName,eo_gateway_api_group.gatewayID,eo_gateway_api_group.parentGroupID,eo_gateway_api_group.isChild) VALUES (?,?,?,1);`)
defer stmt.Close()
if err != nil {
return false,0
}
res, err := stmt.Exec(groupName,gatewayID,parentGroupID)
if err != nil {
return false,0
} else{
id, _ := res.LastInsertId()
return true,int(id)
}
}
// 删除网关api分组
func DeleteGroup(groupID int) bool{
db := database.GetConnection()
Tx,_ := db.Begin()
stmt,err := Tx.Prepare(`DELETE FROM eo_gateway_api_group WHERE eo_gateway_api_group.groupID = ?;`)
defer stmt.Close()
if err != nil {
return false
}
_, err = stmt.Exec(groupID)
if err != nil {
Tx.Rollback()
return false
} else{
stmt,_ = Tx.Prepare("DELETE FROM eo_gateway_api_group WHERE eo_gateway_api_group.parentGroupID = ?;")
stmt.Exec(groupID)
stmt,_ = Tx.Prepare("DELETE FROM eo_gateway_api WHERE eo_gateway_api.groupID = ?;")
stmt.Exec(groupID)
Tx.Commit()
return true
}
}
// 获取网关分组列表
func GetGroupList(gatewayID int) (bool,[]*utils.GroupInfo){
db := database.GetConnection()
rows,err := db.Query(`SELECT eo_gateway_api_group.groupID,eo_gateway_api_group.groupName FROM eo_gateway_api_group WHERE gatewayID = ? AND isChild = 0 ORDER BY eo_gateway_api_group.groupID DESC;`,gatewayID)
defer rows.Close()
groupList := make([]*utils.GroupInfo,0)
flag := true
if err != nil {
flag = false
}
num :=0
//延时关闭Rows
defer rows.Close()
//获取记录列
if _, err = rows.Columns(); err != nil {
return false,groupList
} else {
for rows.Next(){
var group utils.GroupInfo
err:= rows.Scan(&group.GroupID,&group.GroupName);
if err!=nil{
flag = false
break
}
childRows,err := db.Query(`SELECT eo_gateway_api_group.groupID,eo_gateway_api_group.groupName FROM eo_gateway_api_group WHERE gatewayID = ? AND isChild = 1 AND parentGroupID = ? ORDER BY eo_gateway_api_group.groupID DESC;`,gatewayID,group.GroupID)
for childRows.Next(){
var childGroup utils.ChildGroupInfo
childRows.Scan(&childGroup.GroupID,&childGroup.GroupName)
group.ChildGroupList = append(group.ChildGroupList,&childGroup)
}
if group.ChildGroupList == nil{
childGroup := make([]*utils.ChildGroupInfo,0)
group.ChildGroupList = childGroup
}
groupList = append(groupList,&group)
num +=1
}
}
if num == 0{
flag =false
}
return flag,groupList
}
// 修改分组信息
func EditGroup(groupID,parentGroupID int,groupName string) bool{
db := database.GetConnection()
stmt,err := db.Prepare(`UPDATE eo_gateway_api_group SET eo_gateway_api_group.groupName = ?,eo_gateway_api_group.parentGroupID = ?,eo_gateway_api_group.isChild = ? WHERE eo_gateway_api_group.groupID = ?;`)
defer stmt.Close()
if err != nil {
return false
}
isChild := 1
if parentGroupID == 0{
isChild = 0
}
_, err = stmt.Exec(groupName,parentGroupID,isChild ,groupID)
if err != nil {
return false
} else{
return true
}
}
// 判断分组与用户是否匹配
func CheckGroupPermission(groupID,userID int) bool{
db := database.GetConnection()
var gatewayID int
err := db.QueryRow("SELECT eo_conn_management.gatewayID FROM eo_conn_management INNER JOIN eo_gateway_api_group ON eo_gateway_api_group.gatewayID = eo_conn_management.gatewayID WHERE userID = ? AND groupID = ?;",groupID,userID).Scan(&gatewayID)
if err != nil {
return false
} else{
return true
}
}
// 获取分组名称
func GetGroupName(groupID int) (bool,string){
db := database.GetConnection()
var gatewayName string
err := db.QueryRow("SELECT eo_gateway_api_group.groupName FROM eo_gateway_api_group WHERE eo_gateway_api_group.groupID = ?;",groupID).Scan(&gatewayName)
if err != nil {
return false,""
} else{
return true,gatewayName
}
}
// 关键字获取网关分组列表
func GetGroupListByKeyword(keyword string,gatewayID int) (bool,[]*utils.GroupInfo){
db := database.GetConnection()
rows,err := db.Query(`SELECT eo_gateway_api_group.groupID,eo_gateway_api_group.groupName,eo_gateway_api_group.isChild,eo_gateway_api_group.parentGroupID FROM eo_gateway_api_group WHERE gatewayID = ? AND groupName LIKE ? ORDER BY eo_gateway_api_group.groupID DESC;`,gatewayID,"%" + keyword + "%")
defer rows.Close()
groupList := make([]*utils.GroupInfo,0)
flag := true
if err != nil {
flag = false
}
num :=0
//延时关闭Rows
defer rows.Close()
//获取记录列
if _, err = rows.Columns(); err != nil {
return false,groupList
} else {
for rows.Next(){
var group,fatherGroup utils.GroupInfo
var isChild,parentGroupID int
err:= rows.Scan(&group.GroupID,&group.GroupName,&isChild,&parentGroupID);
if err!=nil{
flag = false
break
}
if isChild == 1{
err = db.QueryRow("SELECT groupID,groupName FROM eo_gateway_api_group WHERE groupID = ?;",parentGroupID).Scan(&fatherGroup.GroupID,&fatherGroup.GroupName)
if err != nil{
return false,groupList
}
childGroupList := make([]*utils.ChildGroupInfo,0)
var childGroup utils.ChildGroupInfo
childGroup.GroupID = group.GroupID
childGroup.GroupName = group.GroupName
childGroupList = append(childGroupList,&childGroup)
fatherGroup.ChildGroupList = childGroupList
groupList = append(groupList,&fatherGroup)
}else{
groupList = append(groupList,&group)
}
num +=1
}
}
if num == 0{
flag =false
}
return flag,groupList
}
// 获取接口分组数量
func GetApiGroupCount(gatewayHashKey string) int{
var count int
db := database.GetConnection()
sql := "SELECT COUNT(0) FROM eo_gateway_api_group INNER JOIN eo_gateway ON eo_gateway_api_group.gatewayID = eo_gateway.gatewayID WHERE eo_gateway.hashKey = ?;"
db.QueryRow(sql,gatewayHashKey).Scan(&count)
return count
}
\ No newline at end of file
package dao
import (
"goku-ce-1.0/dao/database"
"goku-ce-1.0/utils"
"encoding/json"
"strconv"
)
func Login(loginCall,loginPassword string) (bool,int){
db := database.GetConnection()
var userID int
err := db.QueryRow("SELECT userID FROM eo_admin WHERE loginCall = ? AND loginPassword = ?;",loginCall,loginPassword).Scan(&userID)
if err != nil{
return false,0
}
return true,userID
}
func Register(loginCall,loginPassword string) (bool){
db := database.GetConnection()
var userID int
err := db.QueryRow("SELECT userID FROM eo_admin WHERE loginCall = ?",loginCall).Scan(&userID)
if err == nil{
return false
}else{
stmt,err:= db.Prepare("INSERT INTO eo_admin (loginCall,loginPassword) VALUES (?,?);")
defer stmt.Close()
_, err = stmt.Exec(loginCall,loginPassword)
if err != nil {
return false
} else{
return true
}
}
}
func CheckUserNameExist(loginCall string) bool{
db := database.GetConnection()
var userID int
err := db.QueryRow("SELECT userID FROM eo_admin WHERE loginCall = ?",loginCall).Scan(&userID)
if err != nil{
return false
}else{
return true
}
}
// 写入登录信息
func ConfirmLoginInfo(userID int,loginCall,userToken string) bool{
redisConn,err := utils.GetRedisConnection()
defer redisConn.Close()
if err != nil{
return false
}
redisInfo := map[string]interface{}{"userID":userID,"loginCall":loginCall,"userToken":userToken}
redisString,err := json.Marshal(redisInfo)
if err != nil{
return false
}
_, err = redisConn.Do("hset","userToken",userToken,string(redisString[:]))
if err != nil{
return false
}
return true
}
func CheckLogin(userID,userToken string) (bool) {
redisConn,err := utils.GetRedisConnection()
if err != nil{
return false
}
defer redisConn.Close()
var redisJson map[string]interface{}
redisInfo,err := redisConn.Do("hget","userToken",userToken)
if redisInfo == nil{
return false
}
val := redisInfo.([]uint8)
redisStr := []byte(string(val))
err = json.Unmarshal(redisStr,&redisJson)
if err != nil{
return true
}
if uid,_ := strconv.Atoi(userID); uid != int(redisJson["userID"].(float64)){
return false
}else{
return true
}
}
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
package dao
import (
"goku-ce-1.0/dao/database"
)
// 修改密码
func EditPassword(userID int,oldPassword,newPassword string) bool{
db := database.GetConnection()
stmt,err := db.Prepare("UPDATE eo_admin SET loginPassword = ? WHERE userID = ? AND loginPassword = ?;")
if err != nil{
return false
}
_,err = stmt.Exec(newPassword,userID,oldPassword)
if err != nil{
return false
}
return true
}
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
group: # API分组
- group_id: 1 # API分组id
group_name: 示例分组 # API分组名称
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册