package handler import ( "fmt" "github.com/gin-gonic/gin" "net/http" "strings" "gitlab.wodcloud.com/apaas/apaas-meshproxy/src/client" "github.com/vulcand/oxy/forward" "github.com/vulcand/oxy/testutils" "gitlab.wodcloud.com/apaas/apaas-meshproxy/src/config" ) var fwd *forward.Forwarder func init() { fwd, _ = forward.New(forward.PassHostHeader(true)) } func Proxy(c *gin.Context) { if err := count(); err != nil { fmt.Println(err.Error()) c.String(200, "缓存计数失败!") return } req := c.Request req.URL = testutils.ParseURI(getProxyURL(req)) req.RequestURI = getRequestURI(req) req.Host = req.URL.Host fmt.Println(req.URL, req.RequestURI, req.Host) fwd.ServeHTTP(c.Writer, req) } func getProxyURL(req *http.Request) string { path := req.URL.Path path = strings.Replace(req.URL.Path, config.Prefix, config.ProxyPath, 1) rawQuery := req.URL.RawQuery var result = "" if rawQuery == "" { result = fmt.Sprintf("http://%s%s", config.ProxyHost, path) } else { result = fmt.Sprintf("http://%s%s?%s", config.ProxyHost, path, rawQuery) if strings.HasSuffix(result, "/") { result = strings.TrimRight(result, "/") } } return result } func getRequestURI(req *http.Request) string { path := req.URL.Path rawQuery := req.URL.RawQuery var result = "" if rawQuery == "" { result = path } else { result = path + "?" + rawQuery } return result } /** 计数 */ func count() error { redis, err := client.GetRedisClient() if err != nil { return err } ic, err := redis.Incr(fmt.Sprintf("%s%s", config.ProxyHost, config.ProxyPath)) _, err = ic.Result() return err }