• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang goproxy.NewResponse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/elazarl/goproxy.NewResponse函数的典型用法代码示例。如果您正苦于以下问题:Golang NewResponse函数的具体用法?Golang NewResponse怎么用?Golang NewResponse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewResponse函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: handleDialDirectConnection

func handleDialDirectConnection(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
	// see who we're gonna call
	req.ParseForm()
	switch req.Method {
	case "POST":
		connectionID := req.Form.Get("connectionID")
		if connectionID == "" {
			log.Printf("Missing connectionID")
			return nil, goproxy.NewResponse(req,
				goproxy.ContentTypeText, http.StatusBadRequest,
				"Missing connectionID.")
		}
		log.Printf("handleDirectConnection has connectionID: %s", connectionID)

		invitation := getInvitation(connectionID)
		if invitation == nil {
			log.Printf("Wrong connectionID")
			return nil, goproxy.NewResponse(req,
				goproxy.ContentTypeText, http.StatusBadRequest,
				"Proxy has been restarted since this page was served. Please log in again.")
		}

		//log.Printf("invitation is: %#v", invitation)

		inviteeName, inviteeHost, err := eccentric.ParseCN(invitation.InviteeCN)
		check(err)
		log.Printf("invitee is: %v, %v", inviteeName, inviteeHost)

		// fetch our own identity
		ourCreds := getLoggedInCreds(inviteeHost)
		if ourCreds == nil {
			// should not happen, as we need to be logged in to get the dial-button, but anyway
			log.Println("Site says to dial a direct connection but you are not logged in.")
			return nil, goproxy.NewResponse(req,
				goproxy.ContentTypeText, http.StatusInternalServerError,
				"Ecca Proxy error: Site says to dial a direct connection but you haven't logged in. Please log in first, then try again.")
		}

		log.Printf("our creds are: %v\n", ourCreds.CN)
		ourCert, err := tls.X509KeyPair(ourCreds.Cert, ourCreds.Priv)
		check(err)
		//log.Printf("ourCert is: %#v", ourCert)

		// call out and show the response
		response := dialDirectConnection(invitation, ourCert)
		return nil, goproxy.NewResponse(req, goproxy.ContentTypeText, http.StatusOK, response)
	}

	log.Printf("Unexpected method: %#v", req.Method)
	return nil, nil
}
开发者ID:gwitmond,项目名称:ecca-proxy,代码行数:51,代码来源:user.go


示例2: requestHanderFunc

func requestHanderFunc(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
	urlOld := r.URL.String()
	log.Println("raw_url->", urlOld)
	r.Header.Set("Connection", "Close")
	r.Header.Del("Proxy-Connection")

	if conf.IsProxyHost(urlOld) {
		log.Println("direct IsProxyHost->", urlOld)
		return r, nil
	}

	proxy := conf.GetOneProxy()
	if proxy == nil {
		log.Println("no proxy")
		return r, goproxy.NewResponse(r, goproxy.ContentTypeHtml, http.StatusBadGateway, "no proxy")
	}

	urlNew, _, err := proxy.GenReqUrl(urlOld)

	if err != nil {
		log.Println("encryptURL", urlOld, "failed", err)
		return r, goproxy.NewResponse(r, goproxy.ContentTypeHtml, http.StatusBadGateway, "encrypt url failed")
	}

	log.Println(urlOld, "--->", urlNew)
	//	var err error
	r.URL, err = url.Parse(urlNew)

	if err != nil {
		log.Println("parse new url failed", err)
		return r, goproxy.NewResponse(r, goproxy.ContentTypeHtml, http.StatusBadGateway, "create url failed,check proxy url")
	}

	r.Host = r.URL.Host

	r.Header.Add("is_client", "1")
	r.Header.Set(kxKey, proxy.SecertKey)
	if conf.HiddenIp {
		r.Header.Set("hidden_ip", "1")
	}

	kxutil.HeaderEnc(r.Header)
	//	body:=r.Body
	//	reader := kxutil.CipherStreamReader(proxy.SecertKey, encodeURL, body)
	//	r.Body = ioutil.NopCloser(reader)
	//	r.Header.Set("_kx_enc_","1")
	//	panic("a")

	return r, nil
}
开发者ID:hidu,项目名称:kx-proxy-client,代码行数:50,代码来源:client.go


示例3: OnRequest

func (h *FilteringHandler) OnRequest(r *http.Request, ctx *goproxy.ProxyCtx) (
	*http.Request, *http.Response) {

	host := r.URL.Host
	if host == "" {
		host = r.Host
	}
	rq := &adblock.Request{
		URL:          r.URL.String(),
		Domain:       host,
		OriginDomain: getReferrerDomain(r),
	}
	rules := h.Cache.Rules()
	start := time.Now()
	matched, id := rules.Matcher.Match(rq)
	end := time.Now()
	duration := end.Sub(start) / time.Millisecond
	if matched {
		rule := rules.Rules[id]
		log.Printf("rejected in %dms: %s\n", duration, r.URL.String())
		log.Printf("  by %s\n", rule)
		return r, goproxy.NewResponse(r, goproxy.ContentTypeText,
			http.StatusNotFound, "Not Found")
	}
	ctx.UserData = &ProxyState{
		Duration: duration,
		URL:      r.URL.String(),
	}
	return r, nil
}
开发者ID:chinanjjohn2012,项目名称:adblock,代码行数:30,代码来源:adstop.go


示例4: main

func main() {

	var templateFilePath string
	if len(os.Args) == 1 {
		templateFilePath = "./template.html"
	} else if len(os.Args) == 2 {
		templateFilePath = os.Args[1]
	} else {
		panic("Unknown number of arguments. Please enter a template file")
	}

	content, err := ioutil.ReadFile(templateFilePath)
	if err != nil {
		panic(err)
	}

	var htmlStr string = string(content)

	proxy := goproxy.NewProxyHttpServer()
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).HandleConnect(goproxy.AlwaysMitm)
	proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
		return req, goproxy.NewResponse(req, goproxy.ContentTypeHtml, http.StatusForbidden, htmlStr)
	})

	log.Fatalln(http.ListenAndServe(":8401", proxy))
}
开发者ID:cztchoice,项目名称:Focus,代码行数:26,代码来源:FocusHTTProxy.go


示例5: initUpstreamProxy

func initUpstreamProxy() {
	go func() {
		proxy := goproxy.NewProxyHttpServer()

		proxy.OnRequest().DoFunc(
			func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
				if !hasExpectedCustomHeaders(r.Header) {
					ctx.Logf("missing expected headers: %+v", ctx.Req.Header)
					return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
				}
				return r, nil
			})

		proxy.OnRequest().HandleConnectFunc(
			func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
				if !hasExpectedCustomHeaders(ctx.Req.Header) {
					ctx.Logf("missing expected headers: %+v", ctx.Req.Header)
					return goproxy.RejectConnect, host
				}
				return goproxy.OkConnect, host
			})

		err := http.ListenAndServe("127.0.0.1:2161", proxy)
		if err != nil {
			fmt.Printf("upstream proxy failed: %s", err)
		}
	}()

	// TODO: wait until listener is active?
}
开发者ID:geebee,项目名称:psiphon-tunnel-core,代码行数:30,代码来源:controller_test.go


示例6: listPackages

func listPackages(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
	val, _, _, err := cn.Get("packages")
	if err != nil {
		return r, nil
	}
	log.Println("MEMCACHED FROM GO SERVER")
	return r, goproxy.NewResponse(r, "application/json", http.StatusOK, val)
}
开发者ID:RCwukaka,项目名称:registry,代码行数:8,代码来源:registry.go


示例7: conf

// display the configuration
func (bl *BlockClock) conf(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
	bl.update()

	return r, goproxy.NewResponse(r,
		goproxy.ContentTypeText,
		http.StatusOK,
		fmt.Sprintf("hosts %s\nstart blocking at: %s", bl.Hosts, bl.LockAt))
}
开发者ID:jweir,项目名称:nogame,代码行数:9,代码来源:nogame.go


示例8: getPackage

func getPackage(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
	elements := strings.Split(r.URL.Path, "/")
	packageName := elements[len(elements)-1]

	var name, url string
	if err := pool.QueryRow("getPackage", packageName).Scan(&name, &url); err != nil {
		if err == pgx.ErrNoRows {
			return r, goproxy.NewResponse(r, "text/html", http.StatusNotFound, "Package not found")
		}
		return r, goproxy.NewResponse(r, "text/html", http.StatusInternalServerError, "Internal server error")
	}

	data, err := json.Marshal(Package{Name: name, URL: url})
	if err != nil {
		return r, goproxy.NewResponse(r, "text/html", http.StatusInternalServerError, "Internal server error")
	}
	return r, goproxy.NewResponse(r, "application/json", http.StatusOK, string(data))
}
开发者ID:RCwukaka,项目名称:registry,代码行数:18,代码来源:registry.go


示例9: getResponse

// getResponse returns stored response from cache
func (d *DBClient) getResponse(req *http.Request) *http.Response {
	log.Info("Returning response")

	key := getRequestFingerprint(req)
	var payload Payload

	payloadBts, err := redis.Bytes(d.cache.get(key))

	if err == nil {
		log.Info("Decoding bytes")
		// getting cache response
		err = json.Unmarshal(payloadBts, &payload)
		if err != nil {
			log.Error(err)
			// what now?
		}

		newResponse := &http.Response{}
		newResponse.Request = req
		// adding headers
		newResponse.Header = make(http.Header)
		if len(payload.Response.Headers) > 0 {
			for k, values := range payload.Response.Headers {
				// headers is a map, appending each value
				for _, v := range values {
					newResponse.Header.Add(k, v)
				}

			}
		}
		newResponse.Header.Set("Gen-Proxy", "Playback")
		// adding body
		buf := bytes.NewBuffer(payload.Response.Body)
		newResponse.ContentLength = int64(buf.Len())
		newResponse.Body = ioutil.NopCloser(buf)

		newResponse.StatusCode = payload.Response.Status

		log.WithFields(log.Fields{
			"key":        key,
			"status":     payload.Response.Status,
			"bodyLength": newResponse.ContentLength,
		}).Info("Response found, returning")

		return newResponse

	} else {
		log.WithFields(log.Fields{
			"error": err.Error(),
		}).Error("Failed to retrieve response from cache")
		// return error? if we return nil - proxy forwards request to original destination
		return goproxy.NewResponse(req,
			goproxy.ContentTypeText, http.StatusPreconditionFailed,
			"Coudldn't find recorded request, please record it first!")
	}

}
开发者ID:rusenask,项目名称:genproxy,代码行数:58,代码来源:models.go


示例10: eccaProxy

// eccaProxy: proxy the user requests and authenticate with the credentials we know.
func eccaProxy(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
	//log.Println("\n\n\nRequest is ", req.Method, req.URL.String())
	ctx.Logf("Start-of-eccaProxy handler")
	for _, c := range req.Cookies() {
		ctx.Logf("Cookie send by the client is: %#v", c.Name)
	}

	// set the scheme to https so we connect upstream securely
	if req.URL.Scheme == "http" {
		req.URL.Scheme = "https"
	}

	// Copy the body because we need it untouched. But we also need to parse
	// the POST parameters and that eats the original buffer with the body
	body, err := ioutil.ReadAll(req.Body)
	check(err)
	req.Body.Close() // close it before replacing. Prevents leaking file descriptors.

	// give the data back immedeately.
	req.Body = ioutil.NopCloser(bytes.NewReader(body))

	// Read the parameters
	req.ParseForm()                                    // eats req.Body
	req.Body = ioutil.NopCloser(bytes.NewReader(body)) // copy back in again

	// Check for POST method with 'encrypt', 'sign' or 'initiate-direct-connection' parameter.
	if req.Method == "POST" {
		if req.Form.Get("initiate-direct-connection") == "required" {
			// create a direct connection listener, awaiting reply
			return initiateDirectConnection(req)
		} else if req.Form.Get("encrypt") == "required" {
			// transparantly encrypt and sign for a private message
			return encryptMessage(req)
		} else if req.Form.Get("sign") == "required" || req.Form.Get("sign") == "optional" {
			// transparently sign the message before publication
			return signMessage(req, ctx)
		}
	}

	// Fetch the request from upstream
	resp, err := fetchRequest(req, ctx)
	if err != nil {
		ctx.Warnf("There was an error fetching the users' request: %v", err)
		return req, goproxy.NewResponse(req,
			goproxy.ContentTypeText, http.StatusInternalServerError,
			"Some server error!")
	}

	ctx.Logf("response is %#v", resp)
	for _, c := range resp.Cookies() {
		ctx.Logf("Cookie send by the server is: %#v\n", c.Name)
	}
	ctx.Logf("End-of-eccaProxy handler")
	//log.Printf("Sleeping for 10 seconds...\n")
	//time.Sleep(10 * time.Second)
	return nil, resp // let goproxy send our response
}
开发者ID:gwitmond,项目名称:ecca-proxy,代码行数:58,代码来源:proxy.go


示例11: OnResponse

func (h *FilteringHandler) OnResponse(r *http.Response,
	ctx *goproxy.ProxyCtx) *http.Response {

	if r == nil {
		// Happens if RoundTrip fails
		return r
	}

	state, ok := ctx.UserData.(*ProxyState)
	if !ok {
		// The request was rejected by the previous handler
		return r
	}

	duration2 := time.Duration(0)
	mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
	if err == nil && len(mediaType) > 0 {
		host := ctx.Req.URL.Host
		if host == "" {
			host = ctx.Req.Host
		}
		rq := &adblock.Request{
			URL:          ctx.Req.URL.String(),
			Domain:       host,
			OriginDomain: getReferrerDomain(ctx.Req),
			ContentType:  mediaType,
			Timeout:      h.MatchTimeout,
		}
		// Second level filtering, based on returned content
		rules := h.Cache.Rules()
		start := time.Now()
		matched, id, err := rules.Matcher.Match(rq)
		if err != nil {
			log.Printf("error: matching %s with domain=%s, origin=%, content-type: %s, "+
				"failed: %s", rq.URL, rq.Domain, rq.OriginDomain, rq.ContentType, err)
		}
		end := time.Now()
		duration2 = end.Sub(start) / time.Millisecond
		if matched {
			r.Body.Close()
			rule := rules.Rules[id]
			log.Printf("rejected in %d/%dms: %s\n", state.Duration, duration2,
				state.URL)
			log.Printf("  by %s\n", rule)
			return goproxy.NewResponse(ctx.Req, goproxy.ContentTypeText,
				http.StatusNotFound, "Not Found")
		}
	}

	if atomic.LoadUint64(logRequests)%2 == 1 {
		logRequest(ctx.Req)
		logResponse(r)
	}
	log.Printf("accepted in %d/%dms: %s\n", state.Duration, duration2, state.URL)
	return r
}
开发者ID:jannson,项目名称:adblock,代码行数:56,代码来源:adstop.go


示例12: responseFromResponseRecorder

func responseFromResponseRecorder(req *http.Request, w *httptest.ResponseRecorder) (*http.Request, *http.Response) {
	resp := goproxy.NewResponse(req, "", w.Code, w.Body.String())
	resp.Header = make(http.Header)
	for key, vals := range w.HeaderMap {
		for _, val := range vals {
			resp.Header.Add(key, val)
		}
	}
	return req, resp
}
开发者ID:postfix,项目名称:whitelistproxy,代码行数:10,代码来源:transparent.go


示例13: main

func main() {
	verbose := flag.Bool("v", false, "should every proxy request be logged to stdout")
	docRoot := flag.String("root", ".", "document root directory")
	address := flag.String("http", ":8080", `HTTP service address (e.g., ":8080")`)
	flag.Parse()
	proxy := goproxy.NewProxyHttpServer()
	proxy.Verbose = *verbose

	proxy.OnRequest(reqMethodIs("GET", "HEAD")).DoFunc(
		func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
			filename := path.Join(*docRoot, ctx.Req.URL.Path)
			if !exists(filename) {
				return req, nil
			}

			bytes, err := ioutil.ReadFile(filename)
			if err != nil {
				ctx.Warnf("%s", err)
				return req, nil
			}
			resp := goproxy.NewResponse(req, "application/octet-stream",
				http.StatusOK, string(bytes))
			ctx.Logf("return response from local %s", filename)
			return req, resp
		})

	proxy.OnResponse(respReqMethodIs("GET", "HEAD")).Do(
		goproxy.HandleBytes(
			func(b []byte, ctx *goproxy.ProxyCtx) []byte {
				if ctx.Req.Method != "GET" || hasRespHeader(ctx.Resp, "Location") {
					return b
				}

				filename := path.Join(*docRoot, ctx.Req.URL.Path)
				if exists(filename) {
					return b
				}

				dir := path.Dir(filename)
				err := os.MkdirAll(dir, 0755)
				if err != nil {
					ctx.Warnf("cannot create directory: %s", dir)
				}

				err = ioutil.WriteFile(filename, b, 0644)
				if err != nil {
					ctx.Warnf("cannot write file: %s", filename)
				}

				ctx.Logf("save cache to %s", filename)

				return b
			}))
	log.Fatal(http.ListenAndServe(*address, proxy))
}
开发者ID:hnakamur,项目名称:goproxy-rubygems-cache,代码行数:55,代码来源:main.go


示例14: getResponse

// getResponse returns stored response from cache
func (d *DBClient) getResponse(req *http.Request) *http.Response {

	reqBody, err := ioutil.ReadAll(req.Body)

	if err != nil {
		log.WithFields(log.Fields{
			"error": err.Error(),
		}).Error("Got error when reading request body")
	}

	key := getRequestFingerprint(req, reqBody)

	payloadBts, err := d.cache.Get([]byte(key))

	if err == nil {
		// getting cache response
		payload, err := decodePayload(payloadBts)
		if err != nil {
			log.WithFields(log.Fields{
				"error": err.Error(),
			}).Error("Failed to decode payload")
		}

		c := NewConstructor(req, *payload)

		if d.cfg.middleware != "" {
			_ = c.ApplyMiddleware(d.cfg.middleware)
		}

		response := c.reconstructResponse()

		log.WithFields(log.Fields{
			"key":        key,
			"status":     payload.Response.Status,
			"bodyLength": response.ContentLength,
		}).Info("Response found, returning")

		return response

	}

	log.WithFields(log.Fields{
		"error":       err.Error(),
		"query":       req.URL.RawQuery,
		"path":        req.URL.RawPath,
		"destination": req.Host,
		"method":      req.Method,
	}).Warn("Failed to retrieve response from cache")
	// return error? if we return nil - proxy forwards request to original destination
	return goproxy.NewResponse(req,
		goproxy.ContentTypeText, http.StatusPreconditionFailed,
		"Coudldn't find recorded request, please record it first!")

}
开发者ID:sponte,项目名称:hoverfly,代码行数:55,代码来源:models.go


示例15: newCachedResponse

func newCachedResponse(shared bool, cacheRequest *cacheRequest, resource *Resource) *http.Response {

	statusCode, contentLength, headers, body, err := newResponseParameters(shared, cacheRequest, resource)

	if err != nil {
		return goproxy.NewResponse(cacheRequest.Request, goproxy.ContentTypeText, http.StatusInternalServerError, "Error calculating age: "+err.Error())
	}

	cachedResponse := newResponse(cacheRequest.Request, statusCode, contentLength, headers, body)

	return cachedResponse
}
开发者ID:taliesins,项目名称:goproxy,代码行数:12,代码来源:cacher.go


示例16: main

func main() {
	verbose := flag.Bool("v", false, "should every proxy request be logged to stdout")
	addr := flag.String("addr", ":8080", "proxy listen address")
	flag.Parse()
	proxy := goproxy.NewProxyHttpServer()
	proxy.Verbose = *verbose

	atc := atc.NewAirTrafficControl()

	responses := make(chan responseStatus)

	go func() {
		for {
			msg := <-responses
			fmt.Println("respons host", msg.host, "status", msg.status, "len", msg.length)

			if isFailure(msg.status) {
				atc.ReportFailure(msg.host)
			} else {
				atc.ReportSuccess(msg.host)
			}
		}
	}()

	proxy.OnRequest().DoFunc(
		func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
			cleared := atc.GetClearance(r.Host)

			if !cleared {
				fmt.Println("NOT CLEARED!")
				return r, goproxy.NewResponse(r,
					goproxy.ContentTypeText, http.StatusGatewayTimeout,
					"circuit broken")
			}

			return r, nil
		})

	proxy.OnResponse().DoFunc(
		func(r *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
			if r != nil {
				responses <- responseStatus{r.Request.Host, r.StatusCode, r.ContentLength}
			} else {
				fmt.Println("response ERROR:", ctx.Error)
				responses <- responseStatus{ctx.Req.Host, -1, -1}
			}
			return r
		})

	fmt.Println("STARTING")
	log.Fatal(http.ListenAndServe(*addr, proxy))
}
开发者ID:rranshous,项目名称:lzyprxy,代码行数:52,代码来源:main.go


示例17: main

func main() {
	proxy := goproxy.NewProxyHttpServer()
	proxy.OnRequest(goproxy.DstHostIs("www.reddit.com")).DoFunc(
		func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
			if h, _, _ := time.Now().Clock(); h >= 8 && h <= 17 {
				return r, goproxy.NewResponse(r,
					goproxy.ContentTypeText, http.StatusForbidden,
					"Don't waste your time!")
			}
			return r, nil
		})
	log.Fatalln(http.ListenAndServe(":8080", proxy))
}
开发者ID:DirkZhao,项目名称:pproxy,代码行数:13,代码来源:noRedditAtWorktime.go


示例18: Execute

func (runCommand *RunCommand) Execute(configLoader ConfigLoader) error {
	config, err := configLoader()

	if err != nil {
		return err
	}

	proxy := goproxy.NewProxyHttpServer()

	//Verbose if either config or RunCommand is set to verbose
	proxy.Verbose = config.Verbose || runCommand.IsVerbose

	var matchCondition = goproxy.ReqConditionFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) bool {
		_, ok := config.Rewrites[req.URL.String()]

		log.Printf("Trying to match %s", req.URL.String())

		if ok {
			log.Printf("Matched %s", req.URL.String())
		}

		return ok
	})

	proxy.OnRequest(matchCondition).DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
		dstFile, _ := config.Rewrites[req.URL.Path]
		fileBytes, err := ioutil.ReadFile(dstFile)
		if err == nil {
			return req, goproxy.NewResponse(req, "text/css", 200, string(fileBytes[:]))
		} else {
			log.Printf("Error reading file %s", dstFile)
			return req, nil
		}
	})

	configChan := proxyconfig.StartWatching(proxyconfig.DefaultConfigFile)

	go func() {
		for {
			config = <-configChan
			proxy.Verbose = config.Verbose
		}
	}()

	log.Printf("Starting proxyserver localhost:8080 with config %+v", *config)
	log.Fatal(http.ListenAndServe(":8080", proxy))

	return nil
}
开发者ID:roelrymenants,项目名称:fileproxy,代码行数:49,代码来源:runcommand.go


示例19: DoHTTPRequest

func DoHTTPRequest(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
	var success bool
	var flowIndex int
	var response string
	success, flowIndex = drymartini.FindOrGenPath(myDryMartini, DefaultCircLength, DefaultCircLength)
	if !success {
		return r, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusInternalServerError, "error building circuit")
	}
	response, success = drymartini.SendData(myDryMartini, flowIndex, r.URL.String())
	if !success {
		log.Printf("there was an error sending the request:%s\n", r.URL.String())
		return r, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusInternalServerError, "error sending request")
	}
	var contentType string = http.DetectContentType([]byte(response))
	dbg.Printf("detected response as having content-type:%s\n", pVerb, contentType)
	dbg.Printf("request url was:%s\n", pVerb, r.URL.String())

	//gotta set the content-type manually, detectContentType doesn't seem to work for .css
	//kept setting it as "text/plain". there's probably a much nice way than this, whatevs. fake it til you make it
	if strings.Contains(r.URL.String(), ".css") {
		contentType = "text/css"
	}
	return r, goproxy.NewResponse(r, contentType, http.StatusOK, response)
}
开发者ID:johhud1,项目名称:KademliaMixNetwork,代码行数:24,代码来源:proxy.main.go


示例20: signMessage

// signMessage signs a message with our current logged in account (private key) and adds the signature to the original request. Then it sends it on to the web site.
func signMessage(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
	cleartext := req.Form.Get("cleartext")
	// cleartext is the message, for now we ignore the title and other fields in the signature

	// get the current logged in account (and private key)
	// TODO: change to use the server certificate Root CA identity. Not the req.URL.Host.
	log.Printf("req.URL.Host is: %v\n ", req.URL.Host)
	creds := getLoggedInCreds(req.URL.Host)

	if creds == nil {
		if req.Form.Get("sign") == "required" {
			log.Println("Form says to sign a message but no user is logged in.\nConfigure server to require login before handing the form.\nHint: Use the ecca.LoggedInHandler.")
			return nil, goproxy.NewResponse(req,
				goproxy.ContentTypeText, http.StatusInternalServerError,
				"Ecca Proxy error: Server says to sign your message but you haven't logged in. Please log in first, then type your message again. Later we might cache your data and redirect you to the login-screen.")
		}

		// creds is nil but signing is optional. Send the current form unchanged to the upstream server.
		// TODO: show this to the user and confirm to prevent mistakes.
		resp, err := fetchRequest(req, ctx)
		check(err)
		return nil, resp
	}

	log.Printf("creds are: %v\n", creds.CN)
	signature, err := Sign(creds.Priv, creds.Cert, cleartext)
	log.Printf("signature is: %#v\n", signature)
	check(err)
	req.Form.Set("signature", signature) // add signature to the request

	// TODO: refactor this duplicate code from encryptMessage
	client2, err := makeClient(req.URL.Host)
	if err != nil {
		log.Println("error is ", err)
		return nil, nil
	}
	log.Printf("Client to send signed message to: %#v\n", client2)

	log.Printf("POSTING Form to service: %#v\n", req.Form)
	resp, err := client2.PostForm(req.URL.String(), req.Form)
	if err != nil {
		log.Println("error is ", err)
		return nil, nil
	}
	return nil, resp
}
开发者ID:gwitmond,项目名称:ecca-proxy,代码行数:47,代码来源:proxy.go



注:本文中的github.com/elazarl/goproxy.NewResponse函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang goproxy.UrlIs函数代码示例发布时间:2022-05-23
下一篇:
Golang goproxy.NewProxyHttpServer函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap