提交 8d9dfdf1 编写于 作者: E eoLinker API Management

v1.0.2

上级 b49ce809
...@@ -94,3 +94,14 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署, ...@@ -94,3 +94,14 @@ GoKu API Gateway CE,支持OpenAPI与微服务管理,支持私有云部署,
修复: 修复:
1. 某个脚本的编码错误。 1. 某个脚本的编码错误。
#### V1.0.2(2018/4/19)
新增:
1. “接口分组”与“接口详情”可选择拼接网关地址与策略组id,方便查看请求地址;
修复:
1. “鉴权方式”里API Key显示错位问题。
2. 修复mysql5.7环境下,sql脚本执行失败
3. 修复访问网关后端服务时,请求提示错误的问题
\ No newline at end of file
...@@ -97,7 +97,9 @@ func CreateRequest(httpRequest *http.Request, info *utils.MappingInfo, queryPara ...@@ -97,7 +97,9 @@ func CreateRequest(httpRequest *http.Request, info *utils.MappingInfo, queryPara
index := strings.Index(httpRequest.RemoteAddr, ":") index := strings.Index(httpRequest.RemoteAddr, ":")
remoteIP := httpRequest.RemoteAddr[:index] remoteIP := httpRequest.RemoteAddr[:index]
fmt.Println("deal with param time:",time.Since(t1)) fmt.Println("deal with param time:",time.Since(t1))
t2 := time.Now()
res, err := request.Send() res, err := request.Send()
fmt.Println("get response time:",time.Since(t2))
if err != nil { if err != nil {
dao.UpdateVisitCount(context, info,remoteIP) dao.UpdateVisitCount(context, info,remoteIP)
dao.UpdateFailureCount(context,info.GatewayHashKey) dao.UpdateFailureCount(context,info.GatewayHashKey)
...@@ -111,14 +113,16 @@ func CreateRequest(httpRequest *http.Request, info *utils.MappingInfo, queryPara ...@@ -111,14 +113,16 @@ func CreateRequest(httpRequest *http.Request, info *utils.MappingInfo, queryPara
for key, values := range res.Headers() { for key, values := range res.Headers() {
httpResponseHeader[key] = values httpResponseHeader[key] = values
} }
t3 := time.Now()
go dao.UpdateVisitCount(context, info,remoteIP) go dao.UpdateVisitCount(context, info,remoteIP)
fmt.Println("update visit count:",time.Since(t3))
t4 := time.Now()
statusCode := res.StatusCode() statusCode := res.StatusCode()
if statusCode == 200 { if statusCode == 200 {
dao.UpdateSuccessCount(context,info.GatewayHashKey) go dao.UpdateSuccessCount(context,info.GatewayHashKey)
}else{ }else{
dao.UpdateFailureCount(context,info.GatewayHashKey) go dao.UpdateFailureCount(context,info.GatewayHashKey)
} }
fmt.Println("create request time:",time.Since(t1)) fmt.Println("update success/failure count:",time.Since(t4))
return res.StatusCode(), res.Body() return res.StatusCode(), res.Body()
} }
package dao package dao
import ( import (
"fmt"
"goku-ce-1.0/dao/cache" "goku-ce-1.0/dao/cache"
"github.com/farseer810/yawf" "github.com/farseer810/yawf"
"github.com/garyburd/redigo/redis" "github.com/garyburd/redigo/redis"
...@@ -22,7 +23,6 @@ func GetGatewayHashKey(context yawf.Context,gatewayAlias string) string { ...@@ -22,7 +23,6 @@ func GetGatewayHashKey(context yawf.Context,gatewayAlias string) string {
var redisKey string = "gatewayHashKey:" + gatewayAlias var redisKey string = "gatewayHashKey:" + gatewayAlias
conn := cache.GetConnection(context) conn := cache.GetConnection(context)
gatewayHashKey, err := redis.String(conn.Do("GET", redisKey)) gatewayHashKey, err := redis.String(conn.Do("GET", redisKey))
if err == redis.ErrNil { if err == redis.ErrNil {
gatewayHashKey = loadGatewayHashKey(gatewayAlias) gatewayHashKey = loadGatewayHashKey(gatewayAlias)
conn.Do("SET", redisKey, gatewayHashKey) conn.Do("SET", redisKey, gatewayHashKey)
......
...@@ -79,6 +79,7 @@ func main() { ...@@ -79,6 +79,7 @@ func main() {
strategy.POST("/editStrategy",controller.EditStrategy) strategy.POST("/editStrategy",controller.EditStrategy)
strategy.POST("/deleteStrategy",controller.DeleteStrategy) strategy.POST("/deleteStrategy",controller.DeleteStrategy)
strategy.POST("/getStrategyList",controller.GetStrategyList) strategy.POST("/getStrategyList",controller.GetStrategyList)
strategy.POST("/getSimpleStrategyList",controller.GetSimpleStrategyList)
} }
auth := web.Group("/Auth") auth := web.Group("/Auth")
{ {
......
...@@ -23,7 +23,6 @@ func isURIMatched(context yawf.Context, incomingURI, testURI string) bool { ...@@ -23,7 +23,6 @@ func isURIMatched(context yawf.Context, incomingURI, testURI string) bool {
func InjectRequestMapping(httpRequest *http.Request, context yawf.Context, func InjectRequestMapping(httpRequest *http.Request, context yawf.Context,
httpResponse http.ResponseWriter, headers yawf.Headers) (bool, string) { httpResponse http.ResponseWriter, headers yawf.Headers) (bool, string) {
var domain, method, scheme, gatewayHashkey, requestURL string var domain, method, scheme, gatewayHashkey, requestURL string
t1 := time.Now()
// TODO: 0 for http, 1 for https // TODO: 0 for http, 1 for https
scheme = "0" scheme = "0"
fmt.Println(httpRequest.RemoteAddr) fmt.Println(httpRequest.RemoteAddr)
...@@ -50,17 +49,13 @@ func InjectRequestMapping(httpRequest *http.Request, context yawf.Context, ...@@ -50,17 +49,13 @@ func InjectRequestMapping(httpRequest *http.Request, context yawf.Context,
gatewayAlias := requestInfo[1] gatewayAlias := requestInfo[1]
strategyKey := requestInfo[2] strategyKey := requestInfo[2]
// 通过网关别名获取网关hashKey // 通过网关别名获取网关hashKey
gatewayHashkey = dao.GetGatewayHashKey(context,gatewayAlias) gatewayHashkey = dao.GetGatewayHashKey(context,gatewayAlias)
if gatewayHashkey == "" { if gatewayHashkey == "" {
httpResponse.WriteHeader(404) httpResponse.WriteHeader(404)
return false, "error gatewayAlias" return false, "error gatewayAlias"
} }
fmt.Println(gatewayHashkey) fmt.Println(gatewayHashkey)
paths := dao.GetAllAPIPaths(context, gatewayHashkey)
fmt.Println(paths) fmt.Println(paths)
var matchedURI string var matchedURI string
gatewayLen := len(requestInfo[1]) + len(requestInfo[2]) + 2 gatewayLen := len(requestInfo[1]) + len(requestInfo[2]) + 2
...@@ -68,11 +63,10 @@ func InjectRequestMapping(httpRequest *http.Request, context yawf.Context, ...@@ -68,11 +63,10 @@ func InjectRequestMapping(httpRequest *http.Request, context yawf.Context,
for _, uri := range paths { for _, uri := range paths {
if uri[0:4] != scheme+":"+method+":" { if uri[0:4] != scheme+":"+method+":" {
continue continue
}else{
flag = true
} }
if isURIMatched(context, requestURL[gatewayLen:], uri[4:]) { if isURIMatched(context, requestURL[gatewayLen:], uri[4:]) {
matchedURI = uri matchedURI = uri
flag = true
} }
} }
if !flag { if !flag {
...@@ -86,6 +80,5 @@ func InjectRequestMapping(httpRequest *http.Request, context yawf.Context, ...@@ -86,6 +80,5 @@ func InjectRequestMapping(httpRequest *http.Request, context yawf.Context,
info := dao.GetMapping(context, gatewayHashkey, matchedURI) info := dao.GetMapping(context, gatewayHashkey, matchedURI)
info.StrategyKey = strategyKey info.StrategyKey = strategyKey
context.Map(info) context.Map(info)
fmt.Println("mapping time:",time.Since(t1))
return true, "" return true, ""
} }
USE $mysql_dbname USE $mysql_dbname
SET FOREIGN_KEY_CHECKS=0; SET FOREIGN_KEY_CHECKS=0;
...@@ -184,8 +183,8 @@ CREATE TABLE `eo_gateway_rate_limit` ( ...@@ -184,8 +183,8 @@ CREATE TABLE `eo_gateway_rate_limit` (
`limitCount` int(11) DEFAULT NULL, `limitCount` int(11) DEFAULT NULL,
`priorityLevel` int(4) unsigned NOT NULL DEFAULT '1', `priorityLevel` int(4) unsigned NOT NULL DEFAULT '1',
`strategyID` int(11) NOT NULL, `strategyID` int(11) NOT NULL,
`createTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `createTime` timestamp NULL,
`updateTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updateTime` timestamp NULL,
`startTime` varchar(255) NOT NULL, `startTime` varchar(255) NOT NULL,
`endTime` varchar(255) NOT NULL, `endTime` varchar(255) NOT NULL,
PRIMARY KEY (`limitID`) PRIMARY KEY (`limitID`)
...@@ -201,8 +200,8 @@ CREATE TABLE `eo_gateway_strategy_group` ( ...@@ -201,8 +200,8 @@ CREATE TABLE `eo_gateway_strategy_group` (
`strategyKey` varchar(255) NOT NULL, `strategyKey` varchar(255) NOT NULL,
`gatewayID` int(11) NOT NULL, `gatewayID` int(11) NOT NULL,
`strategyDesc` varchar(255) DEFAULT NULL, `strategyDesc` varchar(255) DEFAULT NULL,
`updateTime` timestamp NULL DEFAULT NULL, `updateTime` timestamp NULL ,
`createTime` timestamp NULL DEFAULT NULL, `createTime` timestamp NULL ,
`blackList` text, `blackList` text,
`whiteList` text, `whiteList` text,
`chooseType` tinyint(4) NOT NULL DEFAULT '0', `chooseType` tinyint(4) NOT NULL DEFAULT '0',
......
...@@ -5,7 +5,6 @@ import ( ...@@ -5,7 +5,6 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"strconv" "strconv"
"encoding/json" "encoding/json"
"goku-ce-1.0/conf"
) )
// 新增api // 新增api
...@@ -184,8 +183,15 @@ func GetApiListOrderByName(c *gin.Context) { ...@@ -184,8 +183,15 @@ func GetApiListOrderByName(c *gin.Context) {
gID,_ := strconv.Atoi(groupID) gID,_ := strconv.Atoi(groupID)
flag,apiList := module.GetApiListOrderByName(gID) flag,apiList := module.GetApiListOrderByName(gID)
if flag == true{ if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiList":apiList}) flag,gatewayInfo := module.GetSimpleGatewayInfo(gatewayHashKey)
return 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{ }else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"}) c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return return
...@@ -213,9 +219,14 @@ func GetApi(c *gin.Context) { ...@@ -213,9 +219,14 @@ func GetApi(c *gin.Context) {
aID,_ := strconv.Atoi(apiID) aID,_ := strconv.Atoi(apiID)
flag,apiInfo := module.GetApi(aID) flag,apiInfo := module.GetApi(aID)
if flag == true{ if flag == true{
flag,gatewayInfo := module.GetSimpleGatewayInfo(gatewayHashKey)
apiInfo.Port = conf.Configure["eotest_port"] if flag {
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiInfo":apiInfo,}) 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 return
}else{ }else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"}) c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
...@@ -245,8 +256,14 @@ func GetAllApiListOrderByName(c *gin.Context) { ...@@ -245,8 +256,14 @@ func GetAllApiListOrderByName(c *gin.Context) {
_,gatewayID = module.GetIDFromHashKey(gatewayHashKey) _,gatewayID = module.GetIDFromHashKey(gatewayHashKey)
flag,apiList:= module.GetAllApiListOrderByName(gatewayID) flag,apiList:= module.GetAllApiListOrderByName(gatewayID)
if flag == true{ if flag == true{
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiList":apiList}) flag,gatewayInfo := module.GetSimpleGatewayInfo(gatewayHashKey)
return 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{ }else{
c.JSON(200,gin.H{"statusCode":"190000","type":"api"}) c.JSON(200,gin.H{"statusCode":"190000","type":"api"})
return return
......
...@@ -155,3 +155,32 @@ func GetStrategyList(c *gin.Context) { ...@@ -155,3 +155,32 @@ func GetStrategyList(c *gin.Context) {
return 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
}
}
...@@ -233,7 +233,7 @@ func GetGatewayInfo(gatewayHashKey string) (bool,map[string]interface{}){ ...@@ -233,7 +233,7 @@ func GetGatewayInfo(gatewayHashKey string) (bool,map[string]interface{}){
apiGroupCount := GetApiGroupCount(gatewayHashKey) apiGroupCount := GetApiGroupCount(gatewayHashKey)
strategyGroupCount := GetStrategyCount(gatewayHashKey) strategyGroupCount := GetStrategyCount(gatewayHashKey)
return true,map[string]interface{}{"gatewayID":gatewayID,"gatewayName":gatewayName,"gatewayDesc":gatewayDesc,"gatewayStatus":gatewayStatus,"updateTime":updateTime,"gatewayAlias":gatewayAlias,"gatewayPort":gatewayPort,"monitorTime":monitorTime,"apiGroupCount":apiGroupCount,"strategyGroupCount":strategyGroupCount,"redisInfo":redisInfo} 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获取网关别名 // 通过hashKey获取网关别名
...@@ -310,4 +310,18 @@ func GetGatewayInfoByRedis(gatewayHashKey string) interface{}{ ...@@ -310,4 +310,18 @@ func GetGatewayInfoByRedis(gatewayHashKey string) interface{}{
lastUpdateTime := hourStr + strconv.Itoa(hour) + ":" + minuteStr + strconv.Itoa(minute) + ":" + secondStr + strconv.Itoa(second) 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} return map[string]interface{}{"gatewayMinuteCount":gatewayMinuteCount,"gatewayDayCount":gatewayDayCount,"gatewaySuccessCount":gatewaySuccessCount,"gatewayFailureCount":gatewayFailureCount,"lastUpdateTime":lastUpdateTime}
} }
\ No newline at end of file // 获取简易网关信息
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
...@@ -145,4 +145,38 @@ func GetStrategyCount(gatewayHashKey string) int{ ...@@ -145,4 +145,38 @@ func GetStrategyCount(gatewayHashKey string) int{
sql := "SELECT COUNT(0) FROM eo_gateway_strategy_group INNER JOIN eo_gateway ON eo_gateway_strategy_group.gatewayID = eo_gateway.gatewayID WHERE eo_gateway.hashKey = ?;" sql := "SELECT COUNT(0) FROM eo_gateway_strategy_group INNER JOIN eo_gateway ON eo_gateway_strategy_group.gatewayID = eo_gateway.gatewayID WHERE eo_gateway.hashKey = ?;"
db.QueryRow(sql,gatewayHashKey).Scan(&count) db.QueryRow(sql,gatewayHashKey).Scan(&count)
return count return count
}
// 获取简易策略组列表
func GetSimpleStrategyList(gatewayID int) (bool,interface{}){
db := database.GetConnection()
sql := "SELECT strategyID,strategyName,strategyKey FROM eo_gateway_strategy_group WHERE eo_gateway_strategy_group.gatewayID = ? ORDER BY updateTime DESC"
rows,err := db.Query(sql,gatewayID)
if err != nil {
return false,nil
}
num :=0
strategyList := make([]map[string]interface{},0)
//延时关闭Rows
defer rows.Close()
//获取记录列
if _, err = rows.Columns(); err != nil {
return false,nil
} else {
for rows.Next(){
var strategyID int
var strategyName,strategyKey string
err = rows.Scan(&strategyID,&strategyName,&strategyKey)
if err!=nil{
return false,nil
}
strategyList = append(strategyList,map[string]interface{}{"strategyID":strategyID,"strategyName":strategyName,"strategyKey":strategyKey})
num +=1
}
}
if num == 0{
return false,nil
}
return true,strategyList
} }
\ No newline at end of file
...@@ -91,4 +91,9 @@ func GetGatewayAlias(gatewayHashKey string) (bool,string){ ...@@ -91,4 +91,9 @@ func GetGatewayAlias(gatewayHashKey string) (bool,string){
// 查询网关别名是否存在 // 查询网关别名是否存在
func CheckGatewayAliasIsExist(gatewayAlias string) (bool,string){ func CheckGatewayAliasIsExist(gatewayAlias string) (bool,string){
return dao.CheckGatewayAliasIsExist(gatewayAlias) return dao.CheckGatewayAliasIsExist(gatewayAlias)
}
// 获取简易网关信息
func GetSimpleGatewayInfo(gatewayHashKey string) (bool,interface{}) {
return dao.GetSimpleGatewayInfo(gatewayHashKey)
} }
\ No newline at end of file
...@@ -38,3 +38,8 @@ func GetStrategyList(gatewayID int) (bool,interface{}){ ...@@ -38,3 +38,8 @@ func GetStrategyList(gatewayID int) (bool,interface{}){
func CheckStrategyPermission(gatewayID,strategyID int) bool{ func CheckStrategyPermission(gatewayID,strategyID int) bool{
return dao.CheckStrategyPermission(gatewayID,strategyID) return dao.CheckStrategyPermission(gatewayID,strategyID)
} }
// 获取简易策略组列表
func GetSimpleStrategyList(gatewayID int) (bool,interface{}){
return dao.GetSimpleStrategyList(gatewayID)
}
\ No newline at end of file
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
}
#!/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 &
inject @ 33e0aa1c
Subproject commit 33e0aa1cb7c019ccc3fbe049a8262a6403d30504
requests @ 6ac54c9a
Subproject commit 6ac54c9af45a17d1aed076fe55a1567dda23fb3d
yawf @ 134edd89
Subproject commit 134edd89fc7ea690028a2ecd89f282320cb363bb
endless @ 44713403
Subproject commit 447134032cb6a86814f570257390a379982dfc61
redigo @ d1ed5c67
Subproject commit d1ed5c67e5794de818ea85e6b522fda02623a484
sse @ 22d885f9
Subproject commit 22d885f9ecc78bf4ee5d72b937e4bbcdc58e8cae
gin @ 2fbb9711
Subproject commit 2fbb97117cda046278ad34bd7bac35cbc38c68d5
mysql @ 9181e3a8
Subproject commit 9181e3a86a19bacd63e68d43ae8b7b36320d8092
protobuf @ c65a0412
Subproject commit c65a0412e71e8b9b3bfd22925720d23c0f054237
go-isatty @ 6ca4dbf5
Subproject commit 6ca4dbf54d38eea1a992b3c722a76a5d1c4cb25c
go @ 9831f2c3
Subproject commit 9831f2c3ac1068a78f50999a30db84270f647af6
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))
res, err := request.Send()
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
}
go dao.UpdateVisitCount(context, info,remoteIP)
statusCode := res.StatusCode()
if statusCode == 200 {
dao.UpdateSuccessCount(context,info.GatewayHashKey)
}else{
dao.UpdateFailureCount(context,info.GatewayHashKey)
}
fmt.Println("create request time:",time.Since(t1))
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 (
"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)
}
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())
}
package controller
import (
"goku-ce-1.0/utils"
"goku-ce-1.0/server/module"
"github.com/gin-gonic/gin"
"strconv"
"encoding/json"
"goku-ce-1.0/conf"
)
// 新增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{
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiList":apiList})
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{
apiInfo.Port = conf.Configure["eotest_port"]
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiInfo":apiInfo,})
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{
c.JSON(200,gin.H{"statusCode":"000000","type":"api","apiList":apiList})
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 module
import (
"goku-ce-1.0/server/dao"
)
// 新增策略
func AddStrategy(strategyName,strategyDesc string,gatewayID int) (bool,int,string){
return dao.AddStrategy(strategyName,strategyDesc,gatewayID)
}
// 修改策略
func EditStrategy(strategyName,strategyDesc string,gatewayID,strategyID int) (bool){
flag := dao.CheckStrategyPermission(gatewayID,strategyID)
if flag{
return dao.EditStrategy(strategyName,strategyDesc,strategyID)
}else{
return false
}
}
// 删除策略
func DeleteStrategy(gatewayID,strategyID int) (bool){
flag := dao.CheckStrategyPermission(gatewayID,strategyID)
if flag{
return dao.DeleteStrategy(strategyID)
}else{
return false
}
}
// 获取策略列表
func GetStrategyList(gatewayID int) (bool,interface{}){
return dao.GetStrategyList(gatewayID)
}
// 查询操作权限
func CheckStrategyPermission(gatewayID,strategyID int) bool{
return dao.CheckStrategyPermission(gatewayID,strategyID)
}
validator.v8 @ 5f1438d3
Subproject commit 5f1438d3fca68893a817e4a66806cea46a9e4ebf
yaml.v2 @ d670f940
Subproject commit d670f9405373e636a5a2765eea47fac0c9bc91a4
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"
"time"
"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
t1 := time.Now()
// 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
}else{
flag = true
}
if isURIMatched(context, requestURL[gatewayLen:], uri[4:]) {
matchedURI = uri
}
}
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)
fmt.Println("mapping time:",time.Since(t1))
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 NOT NULL DEFAULT '0000-00-00 00:00:00',
`updateTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`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 DEFAULT NULL,
`createTime` timestamp NULL DEFAULT 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"
)
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
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册