Commit c91916a4 authored by leitao.zhang's avatar leitao.zhang

修改代理

parent a498ce3f
package dao package dao
type ServiceApply struct { type ServiceApply struct {
Id int `json:"id" xorm:"id"` Id int `json:"id" xorm:"id"`
Service_id string `json:"service_id" xorm:"service_id"` ServiceId string `json:"service_id" xorm:"service_id"`
User_id int `json:"user_id" xorm:"user_id"` UserId int `json:"user_id" xorm:"user_id"`
Request_count int `json:"request_count" xorm:"request_count"` RequestCount int `json:"request_count" xorm:"request_count"`
ResFields string `json:"res_fields" xorm:"res_fields text"` ResFields string `json:"res_fields" xorm:"res_fields text"`
} }
func (ServiceApply) TableName() string { func (ServiceApply) TableName() string {
......
...@@ -2,19 +2,20 @@ package dao ...@@ -2,19 +2,20 @@ package dao
import "gitlab.wodcloud.com/apaas/apaas-meshproxy/src/tools" import "gitlab.wodcloud.com/apaas/apaas-meshproxy/src/tools"
type Service_request_record struct { type ServiceRequestRecord struct {
Id int `json:"id" xorm:"id"` Id int `json:"id" xorm:"id"`
Service_id int `json:"service_id" xorm:"service_id"` ServiceId int `json:"service_id" xorm:"service_id"`
Apply_id int `json:"apply_id" xorm:"apply_id"` ApplyId int `json:"apply_id" xorm:"apply_id"`
User_id string `json:"user_id" xorm:"user_id"` UserId string `json:"user_id" xorm:"user_id"`
Request_time tools.JsonTime `json:"request_time" xorm:"request_time created"` RequestTime tools.JsonTime `json:"request_time" xorm:"request_time created"`
Date_day int `json:"date_day" xorm:"date_day"` DateDay int `json:"date_day" xorm:"date_day"`
Date_month int `json:"date_month" xorm:"date_month"` DateMonth int `json:"date_month" xorm:"date_month"`
Date_year int `json:"date_year" xorm:"date_year"` DateYear int `json:"date_year" xorm:"date_year"`
Status int `json:"status" xorm:"status"` Status int `json:"status" xorm:"status"`
Error string `json:"error" xorm:"error"` Error string `json:"error" xorm:"error"`
ReqUrl string `json:"req_url" xorm:"req_url"`
} }
func (s Service_request_record) TableName() string { func (s ServiceRequestRecord) TableName() string {
return "service_request_record" return "service_request_record"
} }
...@@ -14,7 +14,9 @@ import ( ...@@ -14,7 +14,9 @@ import (
"gitlab.wodcloud.com/apaas/apaas-meshproxy/src/service" "gitlab.wodcloud.com/apaas/apaas-meshproxy/src/service"
"gitlab.wodcloud.com/apaas/apaas-meshproxy/src/tools" "gitlab.wodcloud.com/apaas/apaas-meshproxy/src/tools"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"net/url"
"strconv" "strconv"
"strings" "strings"
"time" "time"
...@@ -41,91 +43,145 @@ func Proxy(c *gin.Context) { ...@@ -41,91 +43,145 @@ func Proxy(c *gin.Context) {
c.Error(err) c.Error(err)
return return
} }
if proxyData.Second_level != 1 { //proxyData.ReqUrl = "https://apaas3.wodcloud.com/iam/login/#/login"
if proxyData.SecondLevel != 1 {
res := model.WebRes{} res := model.WebRes{}
res.ErrMsg = `服务申请未通过审批,请联系组织管理员或超管审批` res.ErrMsg = `服务申请未通过审批,请联系组织管理员或超管审批`
c.JSON(200, res) c.JSON(200, res)
return return
} }
roundTripper := http.DefaultTransport.(*http.Transport)
roundTripper.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} if proxyData.ServiceEndTime.Before(appT) {
f, _ := forward.New(forward.PassHostHeader(true), forward.RoundTripper(roundTripper), forward.ResponseModifier(func(resp *http.Response) error { res := model.WebRes{}
//Resp = resp res.ErrMsg = `申请的服务已过期`
//判断是否超过调用次数是否可以调用 c.JSON(200, res)
callflag, sensitiveflag, err := service.QueryCallsCount(proxyData) return
if err != nil { }
fmt.Println("err......", err.Error())
return nil //判断是否超过调用次数是否可以调用
} callflag, _, err := service.QueryCallsCount(proxyData)
if callflag == false { if err != nil {
err = errors.New(`调用达到当日限定次数`) fmt.Println("err......", err.Error(), "无法处理调用次数判断")
Return(nil, err, resp) res := model.WebRes{}
res.ErrMsg = `无法处理您的请求`
c.JSON(200, res)
return
}
if callflag {
res := model.WebRes{}
res.ErrMsg = `已达到最大调用量`
c.JSON(200, res)
return
}
//如果是静态文件
if CheckStaticFile(c.Request.URL.Path) {
host := getHost(proxyData.ReqUrl)
fwd, _ := forward.New(forward.PassHostHeader(false))
c.Request.URL = testutils.ParseURI(fmt.Sprintf("%s%s", host, c.Request.URL.Path))
c.Request.RequestURI = getRequestURI(c.Request)
c.Request.Host = host
fwd.ServeHTTP(c.Writer, c.Request)
} else {
roundTripper := http.DefaultTransport.(*http.Transport)
//roundTripper.ForceAttemptHTTP2 = false
roundTripper.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
f, err := forward.New(forward.PassHostHeader(false), forward.RoundTripper(roundTripper), forward.ResponseModifier(func(resp *http.Response) error {
respbody, err1 := ioutil.ReadAll(resp.Body)
if err1 != nil {
log.Println(err1)
return errors.New(`数据读取失败`)
}
var bytesNewBody []byte
//是否需要过滤字段
if proxyData.DataServiceType1 == 5 && proxyData.ResFields != "" && proxyData.ResFields != "[]" {
//读取数据
bytesNewBody = service.FiledFilter(proxyData, respbody)
} else {
bytesNewBody = respbody
}
//放回
resp.Body = ioutil.NopCloser(bytes.NewBuffer(bytesNewBody))
go func() {
defer func() {
err := recover()
if err != nil {
fmt.Println(err)
}
}()
//调用次数统计
if err := service.CallCounts(proxyData); err != nil {
fmt.Println(err)
}
if resp.StatusCode < 400 {
service.RecordCall(proxyData, resp.StatusCode, nil)
} else {
service.RecordCall(proxyData, resp.StatusCode, nil)
}
}()
//是否需要屏蔽敏感字段 仅对数据服务生效 其它服务部进行处理
//if sensitiveflag && proxyData.DataServiceType1 == 5 {
// res = service.SensitiveFilter(proxyData, res)
//}
//计次
//bgn := time.Now()
//fmt.Println(`开始携程:`, bgn)
//go service.CallCounts(proxyData)
//end := time.Since(bgn)
//fmt.Println("结束携程: ", end)
//err = service.CallCounts(proxyData)
//if err != nil {
// Return(nil, err, resp)
// return nil
//}
////个人申请调用计次
//err = service.ApplyCallCounts(proxyData)
//if err != nil {
// Return(nil, err, resp)
// return nil
//}
//Return(res, nil, resp)
//appeT := time.Since(appT)
//fmt.Println("结束: ", appeT)
return nil return nil
}))
if err != nil {
} }
bT := time.Now() c.Request.URL = testutils.ParseURI(proxyData.ReqUrl)
fmt.Println(`开始获取数据:`, bT) fmt.Println("c.Request.URL-------", c.Request.URL)
respbody, _ := ioutil.ReadAll(resp.Body) c.Request.RequestURI = getRequestURI(c.Request)
var res interface{} fmt.Println("c.Request-------", c.Request)
res = respbody c.Request.Host = getHost(proxyData.ReqUrl)
eT := time.Since(bT) fmt.Println("proxyData.RealUrl-------", proxyData.ReqUrl)
fmt.Println("获取数据: ", eT) f.ServeHTTP(c.Writer, c.Request)
//是否需要过滤字段 }
if proxyData.ResFields != "" {
bT := time.Now() }
fmt.Println(`过滤:`, bT)
res = service.FiledFilter(proxyData, respbody) func CheckStaticFile(path string) bool {
eT := time.Since(bT) if strings.HasSuffix(path, ".css") || strings.HasSuffix(path, ".js") || strings.HasSuffix(path, ".woff2") ||
fmt.Println("过滤: ", eT) strings.HasSuffix(path, ".jpg") || strings.HasSuffix(path, ".svg") || strings.HasSuffix(path, ".woff") || strings.HasSuffix(path, ".html") || strings.HasSuffix(path, ".ttf") {
} return true
//是否需要屏蔽敏感字段 }
if sensitiveflag == false { return false
res = service.SensitiveFilter(proxyData, res)
}
//计次
//bgn := time.Now()
//fmt.Println(`开始携程:`, bgn)
go service.CallCounts(proxyData)
//end := time.Since(bgn)
//fmt.Println("结束携程: ", end)
//err = service.CallCounts(proxyData)
//if err != nil {
// Return(nil, err, resp)
// return nil
//}
////个人申请调用计次
//err = service.ApplyCallCounts(proxyData)
//if err != nil {
// Return(nil, err, resp)
// return nil
//}
Return(res, nil, resp)
//appeT := time.Since(appT)
//fmt.Println("结束: ", appeT)
return nil
}))
c.Request.URL = testutils.ParseURI(getProxyURL(proxyData, c.Request))
fmt.Println("c.Request.URL-------", c.Request.URL)
c.Request.RequestURI = getRequestURI(c.Request)
fmt.Println("c.Request-------", c.Request)
c.Request.Host = getHost(proxyData.RealUrl)
fmt.Println("proxyData.RealUrl-------", proxyData.RealUrl)
f.ServeHTTP(c.Writer, c.Request)
} }
func getProxyURL(proxyData model.ProxyData, req *http.Request) string { func getProxyURL(proxyData model.ProxyData, req *http.Request) string {
realPath := proxyData.RealUrl realPath := proxyData.ReqUrl
rawQuery := req.URL.RawQuery rawQuery := req.URL.RawQuery
var result = "" var result = ""
if rawQuery == "" { if rawQuery == "" {
if proxyData.Name == "时空服务" { if proxyData.DataServiceType1 == 6 {
result = realPath + "?f=json" result = realPath + "?f=json"
} else { } else {
result = realPath result = realPath
} }
} else { } else {
result = realPath + "?" + rawQuery result = realPath + "?" + rawQuery
if proxyData.Name == "时空服务" && !strings.Contains(rawQuery, "f=json") { if proxyData.DataServiceType1 == 6 && !strings.Contains(rawQuery, "f=json") {
result = result + "&f=json" result = result + "&f=json"
} }
} }
...@@ -176,20 +232,19 @@ func gzipCompress(content *[]byte) []byte { ...@@ -176,20 +232,19 @@ func gzipCompress(content *[]byte) []byte {
return compressData.Bytes() return compressData.Bytes()
} }
// 获取域名 // 获取域名 protocol :// hostname[:port] / path / [;parameters][?query]#fragment
func getHost(url string) (path string) { func getHost(httpurl string) (path string) {
if strings.Contains(url, "//") { parse, err := url.Parse(httpurl)
path = strings.Split(url, "//")[1] if err != nil {
if strings.Contains(path, "/") { return ""
path = strings.Split(path, "/")[0]
}
} }
return return fmt.Sprintf("%s://%s", parse.Scheme, parse.Host)
} }
func HealthCheck(c *gin.Context) { func HealthCheck(c *gin.Context) {
res := model.WebRes{} res := model.WebRes{}
proxyData, err := service.GetReqPath() apiId := c.Param("apiid")
proxyData, err := service.GetReqPath(apiId)
if err != nil { if err != nil {
res.Data = err.Error() res.Data = err.Error()
c.JSON(500, res) c.JSON(500, res)
......
...@@ -18,11 +18,11 @@ import ( ...@@ -18,11 +18,11 @@ import (
var ( var (
argPort = pflag.Int("port", 8011, "") argPort = pflag.Int("port", 8011, "")
argPrefix = pflag.String("prefix", "/bgmesh/fiddler", "") argPrefix = pflag.String("prefix", "/bgmesh/fiddler", "")
meshId = pflag.String("meshId", "149", "") meshId = pflag.String("meshId", "133", "")
redisUrl = pflag.String("redisUrl", "redis://redis.apaas-v3:6379", "") redisUrl = pflag.String("redisUrl", "redis://apaas-redis:6379", "")
redisTag = pflag.String("redisTag", "apaas-mesh-proxy", "") redisTag = pflag.String("redisTag", "apaas-mesh-proxy", "")
confPath = pflag.String("confPath", "/app/config/proxy.json", "") confPath = pflag.String("confPath", "/app/config/proxy.json", "")
dbURL = pflag.String("dbURL", "host=stolon-proxy.devops port=5432 user=postgres password=spaceIN511 dbname=apaas sslmode=disable", "") dbURL = pflag.String("dbURL", "host=apaas-postgis.apaas-v3 port=54321 user=postgres password=passwd123 dbname=apaas sslmode=disable", "")
dbDriverName = pflag.String("dbDriverName", "postgres", "") dbDriverName = pflag.String("dbDriverName", "postgres", "")
) )
......
package model package model
import "time"
type ProxyData struct { type ProxyData struct {
RealUrl string `json:"req_url" xorm:"req_url"` ApplyId int64 `json:"apply_id"`
ResFields string `json:"res_fields" xorm:"res_fields text"` ReqUrl string `json:"req_url"`
Count int `json:"count" xorm:"count"` RequestCount int64 `json:"request_count"`
Sensituve_word string `json:"sensituve_word" xorm:"sensituve_word"` Duration int64 `json:"duration"`
Sensitive_count int `json:"sensitive_count" xorm:"sensitive_count"` DurationUnit int64 `json:"duration_unit"`
Apply_id int `json:"apply_id" xorm:"apply_id"` SpcsType int `json:"spcs_type"`
Service_id int `json:"service_id" xorm:"service_id"` SpcsCount int64 `json:"spcs_count"`
User_id string `json:"user_id" xorm:"user_id"` ResFields string `json:"res_fields"`
Data_service_type1 int `json:"data_service_type1" xorm:"data_service_type1"` DataServiceType1 int64 `json:"data_service_type1"`
Name string `json:"name"` DataServiceType2 int64 `json:"data_service_type2"`
Second_level int `json:"second_level"xorm:"second_level"` DataServiceType3 int64 `json:"data_service_type3"`
SecondLevel int64 `json:"second_level"`
ServiceEndTime time.Time `json:"service_end_time"`
ReqName string `json:"req_name"`
ServiceState int64 `json:"service_state"`
PayStatus int64 `json:"pay_status"`
ApplyUserId string `json:"apply_user_id"`
ServiceUserId string `json:"service_user_id"`
ServiceOid string `json:"service_oid"`
ApplyOid string `json:"apply_oid"`
SensituveWord string `json:"sensituve_word"`
SensitiveCount int64 `json:"sensitive_count"`
ServiceId int64 `json:"service_id"`
ApiId int64 `json:"api_id"` //接口ID
} }
type WebRes struct { type WebRes struct {
......
...@@ -32,9 +32,12 @@ func Load(middleware ...gin.HandlerFunc) http.Handler { ...@@ -32,9 +32,12 @@ func Load(middleware ...gin.HandlerFunc) http.Handler {
e.Use(middleware...) e.Use(middleware...)
root := e.Group(fmt.Sprintf("%s/%s", config.Prefix, config.MeshId)) root := e.Group(fmt.Sprintf("%s/%s", config.Prefix, config.MeshId))
{ {
root.GET("/health", handler.HealthCheck) //root.GET("/health", handler.HealthCheck)
root.Any("/service/:applyId", handler.Proxy) root.GET("/health/:apiid/*any", handler.HealthCheck)
//root.Any("/service/:applyId", handler.Proxy)
root.Any("/service/:applyId/:apiid", handler.Proxy) root.Any("/service/:applyId/:apiid", handler.Proxy)
root.Any("/service/:applyId/:apiid/*any", handler.Proxy)
//root.GET("/static/*any", handler.StaticProxy)
} }
return e return e
} }
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment