package handler import ( "bytes" "encoding/json" "github.com/gin-gonic/gin" "github.com/vulcand/oxy/forward" "github.com/vulcand/oxy/testutils" "gitlab.wodcloud.com/apaas/apaas-meshproxy/src/service" "io/ioutil" "net/http" "strconv" "strings" ) var Resp *http.Response func Proxy(c *gin.Context) { appId := c.Param("appId") // TODO 根据appId 获取真实地址 proxyData, err := service.GetRealPath(appId) if err != nil { c.Error(err) return } f, _ := forward.New(forward.PassHostHeader(true), forward.ResponseModifier(func(resp *http.Response) error { Resp = resp // 判断调用是否到达上限 callflag, sensitiveflag, err := service.QueryCallsCount(appId, proxyData) if callflag == false { Return(`调用达到当日限定次数`) return nil } respbody, _ := ioutil.ReadAll(resp.Body) //筛选字段 model := make(map[string]interface{}) realData := make(map[string]interface{}) json.Unmarshal([]byte(proxyData.ResFields), &model) json.Unmarshal(respbody, &realData) res := service.Change(model, realData) if err != nil { Return(err.Error()) return nil } // TODO 筛选过滤敏感字段 if sensitiveflag == false { Sensituve_word := make(map[string]interface{}) json.Unmarshal([]byte(proxyData.Sensituve_word), &Sensituve_word) res = service.FilterSensituveField(Sensituve_word, res) } Return(res) return nil })) c.Request.URL = testutils.ParseURI(proxyData.RealUrl) c.Request.RequestURI = proxyData.RealUrl c.Request.Host = getHost(proxyData.RealUrl) f.ServeHTTP(c.Writer, c.Request) } func Return(res interface{}) { var b []byte switch res.(type) { case []byte: b = res.([]byte) case interface{}: b, _ = json.Marshal(res) } Resp.Header.Set("X-Log-By", "Apaas") l := strconv.Itoa(len(b)) Resp.Header.Set("Content-Length", l) Resp.Body = ioutil.NopCloser(bytes.NewBuffer(b)) } // 获取域名 func getHost(url string) (path string) { if strings.Contains(url, "//") { path = strings.Split(url, "//")[1] if strings.Contains(path, "/") { path = strings.Split(path, "/")[0] } } return }