package handler import ( "fmt" "github.com/sirupsen/logrus" "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" ) // ProxyHandler , a proxy handler type ProxyHandler struct { forward *forward.Forwarder } // CreateProxyHandler , a proxy handler func CreateProxyHandler() (*ProxyHandler, error) { handler := new(ProxyHandler) fwd, _ := forward.New(forward.PassHostHeader(true)) handler.forward = fwd ch = make(chan bool, 1) return handler, nil } var ch chan bool func (handler *ProxyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { logrus.Info("===>", req.URL) if err := count(); err != nil { fmt.Println(err.Error()) w.Write([]byte("缓存计数失败!")) return } req.URL = testutils.ParseURI(handler.getProxyURL(req)) req.RequestURI = handler.getRequestURI(req) req.Host = req.URL.Host fmt.Println(req.URL, req.RequestURI, req.Host) handler.forward.ServeHTTP(w, req) } func (handler *ProxyHandler) 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) } return result } func (handler *ProxyHandler) 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 }