Пример #1
0
func (c *CacheItem) GetResponse() *http.Response {
	r := c.ResponseStates[c.currentState]
	if r.NextState != "" {
		logger.Debug("Switch from state \"" + c.currentState + "\" to state \"" + r.NextState + "\"")
		c.currentState = r.NextState
	}

	ret := c.dispatchReturn(r.Return)

	rbuf := httper.NewResponse(ret)
	code, _ := strconv.Atoi(rbuf.Header.Code)
	vMaj, _ := strconv.Atoi(rbuf.Header.Major)
	vMin, _ := strconv.Atoi(rbuf.Header.Minor)
	h := http.Header{}
	for _, v := range rbuf.Header.Headers {
		h.Add(v.Key, v.Value)
	}
	h.Add("X-Cacher", "In-The-Middle")

	resp := &http.Response{
		Status:     fmt.Sprintf("%s %s", rbuf.Header.Code, rbuf.Header.Message),
		StatusCode: code,
		Proto:      fmt.Sprintf("%s/%s", rbuf.Header.Protocol, rbuf.Header.Version),
		Header:     h,
		ProtoMajor: vMaj,
		ProtoMinor: vMin,
		Body:       ioutil.NopCloser(bytes.NewBufferString(rbuf.Payload)),
	}
	return resp
}
Пример #2
0
func startInTheMiddle(args Args) {
	proxy.WaitForExitSignal()
	tr := transport.Transport{Proxy: transport.ProxyFromEnvironment}
	proxy.Start(proxy.Options{
		Ip:           args.Ip,
		Port:         args.Port,
		ExportFolder: args.ExportFolder,
		Record:       args.Record,
		OnRequest: func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
			ctx.RoundTripper = goproxy.RoundTripperFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (resp *http.Response, err error) {
				ctx.UserData, resp, err = tr.DetailedRoundTrip(req)
				return
			})

			reqBody, err := httputil.DumpRequest(req, true)
			if err != nil {
				logger.Error(err)
				os.Exit(1)
			}

			r := httper.NewRequest(string(reqBody))

			logger.Info(inPFunc("--> ") + r.ToString())

			if !args.Record {
				resp, err := cacher.Find(req)
				if err == nil {
					logger.Debug("Cache HIT")
					return req, resp
				}
				logger.Debug("Cache MISSED")
			}

			return req, nil
		},
		OnResponse: func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
			respBody, err := httputil.DumpResponse(resp, true)
			if err != nil {
				logger.Error(err)
				os.Exit(1)
			}

			r := httper.NewResponse(string(respBody))

			logger.Info(outPFunc("<-- ") + r.ToString())
			return resp
		},
	})
}