當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Request.Close方法代碼示例

本文整理匯總了Golang中net/http.Request.Close方法的典型用法代碼示例。如果您正苦於以下問題:Golang Request.Close方法的具體用法?Golang Request.Close怎麽用?Golang Request.Close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在net/http.Request的用法示例。


在下文中一共展示了Request.Close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: ServeHTTP

func (h *healthcheck) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	proxyWriter, ok := rw.(utils.ProxyResponseWriter)
	var accessLogRecord *schema.AccessLogRecord
	if ok {
		alr := proxyWriter.Context().Value("AccessLogRecord")
		if alr == nil {
			h.logger.Error("AccessLogRecord not set on context", errors.New("failed-to-access-log-record"))
		}
		accessLogRecord = alr.(*schema.AccessLogRecord)
	}
	if h.userAgent == "" || r.Header.Get("User-Agent") == h.userAgent {
		rw.Header().Set("Cache-Control", "private, max-age=0")
		rw.Header().Set("Expires", "0")

		draining := atomic.LoadInt32(h.heartbeatOK) == 0
		if !draining {
			rw.WriteHeader(http.StatusOK)
			rw.Write([]byte("ok\n"))
			r.Close = true
			if ok {
				accessLogRecord.StatusCode = http.StatusOK
			}
		} else {
			rw.WriteHeader(http.StatusServiceUnavailable)
			r.Close = true
			if ok {
				accessLogRecord.StatusCode = http.StatusServiceUnavailable
			}
		}
		return
	}
	next(rw, r)
}
開發者ID:cloudfoundry,項目名稱:gorouter,代碼行數:33,代碼來源:healthcheck.go

示例2: materialHandler

func materialHandler(key string, w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		panic("expected GET")
	}

	untrustedDocName, err := url.QueryUnescape(r.URL.RawQuery)
	if err != nil {
		panic(err)
	}

	log.Printf("%v downloaded %v", key, untrustedDocName)

	// TODO(arjun): this is no longer a file path, but a URL fragment, I think
	docDir, docName := filepath.Split(untrustedDocName)
	if docDir != "" {
		log.Printf("%v SECURITY ERROR %v trying to read document %v", r.RemoteAddr,
			key, untrustedDocName)
		w.WriteHeader(http.StatusBadRequest)
		r.Close = true
		return
	}

	log.Printf("%v %v downloaded %v", r.RemoteAddr, key, docName)
	w.Header().Add("Content-Disposition",
		fmt.Sprintf("inline; filename = %q", docName))
	w.Header().Add("Content-Type", "application/pdf")
	err = dept.DownloadFile(docName, w)
	if err != nil {
		log.Printf("dept.DownloadFile(%v, _) error: %v", docName, err)
		w.WriteHeader(http.StatusBadRequest)
		r.Close = true
	}
}
開發者ID:nimishgupta,項目名稱:Apply2,代碼行數:33,代碼來源:server.go

示例3: delHighlightHandler

func delHighlightHandler(key string, w http.ResponseWriter, r *http.Request) {
	var arg FetchCommentsEnv
	err := util.StringToJSON(key, &arg)
	if err != nil {
		log.Printf("FATAL ERROR decoding closure %v in setScoreHandler", key)
		w.WriteHeader(500)
		return
	}
	if r.Method != "POST" {
		log.Printf("%v SECURITY ERROR %v trying to %v to %v", r.RemoteAddr,
			arg.ReviewerId, r.Method, r.URL)
		w.WriteHeader(http.StatusBadRequest)
		r.Close = true
		return
	}
	err = dept.DelHighlight(arg.AppId, string(arg.ReviewerId))
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		r.Close = true
		log.Printf("%v ERROR DelHighlight(%v, %v): %v", r.RemoteAddr, arg.AppId,
			arg.ReviewerId, err)
		return
	}
	w.WriteHeader(200)
}
開發者ID:nimishgupta,項目名稱:Apply2,代碼行數:25,代碼來源:server.go

示例4: findPageToRender

// Given a request, follow the segments through sitetree to find the page that is being requested. Doesn't
// understand actions, so just finds the page. Returns ID of SiteTree_Live record or 0 if it can't find a
// matching page.
// @todo Understand BaseController actions, or break on the furthest it gets up the tree
// @todo cache site tree
func findPageToRender(r *http.Request) (int, error) {
	siteCache := getSiteCache()
	if siteCache != nil {
		id, found := siteCache.findPageToRender(r)
		if found {
			// fmt.Printf("page cache hit %d\n", id)
			return id, nil
		}
	}

	s := strings.Trim(r.URL.Path, "/")
	path := strings.Split(s, "/")

	if len(path) == 0 || path[0] == "" {
		// find a home page ID
		r, e := orm.Query("select \"ID\" from \"SiteTree_Live\" where \"URLSegment\"='home' and \"ParentID\"=0")
		defer r.Close()

		if e != nil {
			return 0, e
		}
		if !r.Next() {
			return 0, nil
		}

		var ID int
		e = r.Scan(&ID)

		return ID, e
	}

	currParentID := 0
	for _, p := range path {
		r, e := orm.Query("select \"ID\",\"ParentID\" from \"SiteTree_Live\" where \"URLSegment\"='" + p + "' and \"ParentID\"=" + strconv.Itoa(currParentID))
		defer r.Close()

		if e != nil {
			return 0, e
		}
		if !r.Next() {
			return 0, nil
		}

		var ID, ParentID int
		e = r.Scan(&ID, &ParentID)
		currParentID = ID
	}

	// if we get to the end, we've found a matching ID in SiteTree_Live
	return currParentID, nil
}
開發者ID:mrmorphic,項目名稱:goss,代碼行數:56,代碼來源:contentcontroller.go

示例5: OfferingList

// OfferingList parse the yaml files from the repository configuration file defined in the seettings package
// And then returns it json representation
func OfferingList(r *http.Request) (int, []byte, error) {
	settings := settings.Get()
	rootRepository := settings.OfferingRepositoryPath
	var response []byte
	sendOffering := func(path string, info os.FileInfo, err error) error {
		stat, err := os.Stat(path)
		if err != nil {
			return err

		}

		if stat.IsDir() && path != rootRepository {
			return filepath.SkipDir

		}
		matched, err := filepath.Match("*.yaml", info.Name())
		if err != nil {
			return err // this is fatal.

		}
		if matched {
			r, err := os.Open(path)
			if err != nil {
				return err
			}
			data, err := ioutil.ReadAll(r)
			defer r.Close()
			if err != nil {
				return err
			}
			var nodeTypes map[string]toscalib.NodeType
			err = yaml.Unmarshal(data, &nodeTypes)
			if err != nil {
				return err
			}
			response, err = json.MarshalIndent(nodeTypes, "", "  ")
			if err != nil {
				return err
			}
		}
		return nil

	}
	err := filepath.Walk(rootRepository, sendOffering)
	if err != nil {
		log.Println(err)
		return http.StatusInternalServerError, nil, err
	}
	return http.StatusOK, response, nil
}
開發者ID:owulveryck,項目名稱:restmdw,代碼行數:52,代碼來源:offering.go

示例6: post

func post(url_ string, oauthHeaders map[string]string) (r *http.Response, err error) {
	var req http.Request
	req.Method = "POST"
	req.ProtoMajor = 1
	req.ProtoMinor = 1
	req.Close = true
	req.Header = map[string][]string{
		"Authorization": {"OAuth "},
	}
	req.TransferEncoding = []string{"chunked"}

	first := true
	for k, v := range oauthHeaders {
		if first {
			first = false
		} else {
			req.Header["Authorization"][0] += ",\n    "
		}
		req.Header["Authorization"][0] += k + "=\"" + v + "\""
	}

	req.URL, err = url.Parse(url_)
	if err != nil {
		return nil, err
	}

	return send(&req)
}
開發者ID:alloy-d,項目名稱:goauth,代碼行數:28,代碼來源:http.go

示例7: proxyAsync

func proxyAsync(tlsConfig *tls.Config, addr string, w http.ResponseWriter, r *http.Request, callback func(*http.Response)) error {
	log.WithFields(log.Fields{"request": fmt.Sprintf("%+v", r)}).Debug("proxyAsync")
	// Use a new client for each request
	client, scheme := newClientAndScheme(tlsConfig)
	// RequestURI may not be sent to client
	r.RequestURI = ""

	r.URL.Scheme = scheme
	r.URL.Host = addr
	r.Close = true
	log.WithFields(log.Fields{"method": r.Method, "url": r.URL}).Debug("Proxy request")
	resp, err := client.Do(r)
	if err != nil {
		log.WithFields(log.Fields{"request": r, "error": err}).Error("proxyAsync:client.Do(r)")
		return err
	}

	copyHeader(w.Header(), resp.Header)
	w.WriteHeader(resp.StatusCode)
	io.Copy(NewWriteFlusher(w), resp.Body)

	if callback != nil {
		callback(resp)
	}

	// cleanup
	resp.Body.Close()
	log.WithFields(log.Fields{"method": r.Method, "url": r.URL}).Debug("Proxy request: closeIdleConnections(client)....")
	closeIdleConnections(client)
	log.WithFields(log.Fields{"method": r.Method, "url": r.URL}).Debug("Proxy request: closeIdleConnections(client)....Done")
	return nil
}
開發者ID:polyverse-security,項目名稱:swarm,代碼行數:32,代碼來源:utils.go

示例8: rewriteRequest

// This function alters the original request - adds/removes headers, removes hop headers,
// changes the request path.
func rewriteRequest(req *http.Request, cmd *command.Forward, upstream *command.Upstream) *http.Request {
	outReq := new(http.Request)
	*outReq = *req // includes shallow copies of maps, but we handle this below

	outReq.URL.Scheme = upstream.Scheme
	outReq.URL.Host = fmt.Sprintf("%s:%d", upstream.Host, upstream.Port)
	if len(cmd.RewritePath) != 0 {
		outReq.URL.Path = cmd.RewritePath
	}

	outReq.URL.RawQuery = req.URL.RawQuery

	outReq.Proto = "HTTP/1.1"
	outReq.ProtoMajor = 1
	outReq.ProtoMinor = 1
	outReq.Close = false

	glog.Infof("Proxying request to: %v", outReq)

	outReq.Header = make(http.Header)
	netutils.CopyHeaders(outReq.Header, req.Header)

	if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
		// TODO(pquerna): configure this?  Not all backends properly parse the header..
		if TRUST_FORWARD_HEADER {
			if prior, ok := outReq.Header["X-Forwarded-For"]; ok {
				clientIP = strings.Join(prior, ", ") + ", " + clientIP
			}
		}
		outReq.Header.Set("X-Forwarded-For", clientIP)
	}

	if req.TLS != nil {
		outReq.Header.Set("X-Forwarded-Proto", "https")
	} else {
		outReq.Header.Set("X-Forwarded-Proto", "http")
	}

	if req.Host != "" {
		outReq.Header.Set("X-Forwarded-Host", req.Host)
	}

	outReq.Header.Set("X-Forwarded-Server", vulcanHostname)

	if len(cmd.RemoveHeaders) != 0 {
		netutils.RemoveHeaders(cmd.RemoveHeaders, outReq.Header)
	}

	// Add generic instructions headers to the request
	if len(cmd.AddHeaders) != 0 {
		glog.Info("Proxying instructions headers:", cmd.AddHeaders)
		netutils.CopyHeaders(outReq.Header, cmd.AddHeaders)
	}

	// Remove hop-by-hop headers to the backend.  Especially
	// important is "Connection" because we want a persistent
	// connection, regardless of what the client sent to us.
	netutils.RemoveHeaders(hopHeaders, outReq.Header)
	return outReq
}
開發者ID:johntdyer,項目名稱:golang-devops-stuff,代碼行數:62,代碼來源:proxy.go

示例9: copyRequest

func (f *Forwarder) copyRequest(req *http.Request, u *url.URL) *http.Request {
	outReq := new(http.Request)
	*outReq = *req // includes shallow copies of maps, but we handle this below

	outReq.URL = utils.CopyURL(req.URL)
	outReq.URL.Scheme = u.Scheme
	outReq.URL.Host = u.Host
	// workaround for https://github.com/golang/go/issues/10433
	outReq.URL.Opaque = mergeStartingSlashes(req.RequestURI)
	// raw query is already included in RequestURI, so ignore it to avoid dupes
	outReq.URL.RawQuery = ""
	// Do not pass client Host header unless optsetter PassHostHeader is set.
	if f.passHost != true {
		outReq.Host = u.Host
	}
	outReq.Proto = "HTTP/1.1"
	outReq.ProtoMajor = 1
	outReq.ProtoMinor = 1

	// Overwrite close flag so we can keep persistent connection for the backend servers
	outReq.Close = false

	outReq.Header = make(http.Header)
	utils.CopyHeaders(outReq.Header, req.Header)

	if f.rewriter != nil {
		f.rewriter.Rewrite(outReq)
	}
	return outReq
}
開發者ID:narma,項目名稱:oxy,代碼行數:30,代碼來源:fwd.go

示例10: jsonRPCRead

// jsonRPCRead is the RPC wrapper around the jsonRead function to handles
// reading and responding to RPC messages.
func jsonRPCRead(w http.ResponseWriter, r *http.Request, s *rpcServer) {
	r.Close = true
	if atomic.LoadInt32(&s.shutdown) != 0 {
		return
	}
	body, err := btcjson.GetRaw(r.Body)
	if err != nil {
		log.Errorf("RPCS: Error getting json message: %v", err)
		return
	}

	// Error is intentionally ignored here.  It's used in in the
	// websocket handler to tell when a method is not supported by
	// the standard RPC API, and is not needed here.  Error logging
	// is done inside jsonRead, so no need to log the error here.
	reply, _ := jsonRead(body, s, nil)
	log.Tracef("[RPCS] reply: %v", reply)

	msg, err := btcjson.MarshallAndSend(reply, w)
	if err != nil {
		log.Errorf(msg)
		return
	}
	log.Debugf(msg)
}
開發者ID:Belxjander,項目名稱:btcd,代碼行數:27,代碼來源:rpcserver.go

示例11: Do

func (c *Client) Do(request *http.Request) (*http.Response, error) {
	for headerKey, headerVal := range c.Authly.AuthMap {
		request.Header.Add(headerKey, headerVal)
	}
	request.Close = true
	response, err := c.HTTPClient.Do(request)

	if err != nil {
		return nil, err
	}
	supported := response.Header.Get(c.versionHeader)
	format := `################################################################

WARNING: You're using an unsupported version of %s.

You must have at least version %s, your current
version is %s.

################################################################

`
	if !validateVersion(supported, c.currentVersion) {
		fmt.Println(format)
		fmt.Println(supported)
	}
	if response.StatusCode > 399 {
		defer response.Body.Close()
		result, _ := ioutil.ReadAll(response.Body)
		return response, errors.New(string(result))
	}
	return response, nil

}
開發者ID:vijaykanthm28,項目名稱:libgo,代碼行數:33,代碼來源:clients.go

示例12: main

func main() {
	f, err := os.OpenFile("./file.exe", os.O_RDWR, 0666) //其實這裏的 O_RDWR應該是 O_RDWR|O_CREATE,也就是文件不存在的情況下就建一個空文件,但是因為windows下還有BUG,如果使用這個O_CREATE,就會直接清空文件,所以這裏就不用了這個標誌,你自己事先建立好文件。
	if err != nil {
		panic(err)
	}
	stat, err := f.Stat() //獲取文件狀態
	if err != nil {
		panic(err)
	}
	f.Seek(stat.Size(), 0) //把文件指針指到文件末,當然你說為何不直接用 O_APPEND 模式打開,沒錯是可以。我這裏隻是試驗。
	url := "http://dl.google.com/chrome/install/696.57/chrome_installer.exe"
	var req http.Request
	req.Method = "GET"
	//req.UserAgent = UA
	req.Close = true
	req.URL, err = http.ParseURL(url)
	if err != nil {
		panic(err)
	}
	header := http.Header{}
	header.Set("Range", "bytes="+strconv.Itoa64(stat.Size)+"-")
	req.Header = header
	resp, err := http.DefaultClient.Do(&req)
	if err != nil {
		panic(err)
	}
	written, err := io.Copy(f, resp.Body)
	if err != nil {
		panic(err)
	}
	println("written: ", written)
}
開發者ID:bonly,項目名稱:exercise,代碼行數:32,代碼來源:20110905_download.go

示例13: copyRequest

func (proxy *Proxy) copyRequest(r *http.Request) *http.Request {
	proxyRequest := new(http.Request)
	*proxyRequest = *r
	proxyRequest.Proto = "HTTP/1.1"
	proxyRequest.ProtoMajor = 1
	proxyRequest.ProtoMinor = 1
	proxyRequest.Close = false
	proxyRequest.Header = make(http.Header)
	proxyRequest.URL.Scheme = "http"
	proxyRequest.URL.Path = r.URL.Path

	for key, values := range r.Header {
		for _, value := range values {
			proxyRequest.Header.Add(key, value)
		}
	}
	for _, headerName := range ignoredHeaderNames {
		proxyRequest.Header.Del(headerName)
	}
	if requestHost, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
		if values, ok := proxyRequest.Header["X-Forwarded-For"]; ok {
			requestHost = strings.Join(values, ", ") + ", " + requestHost
		}
		proxyRequest.Header.Set("X-Forwarded-For", requestHost)
	}

	return proxyRequest
}
開發者ID:corrupt952,項目名稱:courier,代碼行數:28,代碼來源:courier.go

示例14: copyRequest

// copyRequest creates a new proxy request with some modifications from an original request.
func copyRequest(originalRequest *http.Request) *http.Request {
	pr := new(http.Request)
	*pr = *originalRequest
	pr.Proto = "HTTP/1.1"
	pr.ProtoMajor = 1
	pr.ProtoMinor = 1
	pr.Close = false
	pr.Header = make(http.Header)
	pr.URL.Scheme = "http"
	pr.URL.Path = originalRequest.URL.Path

	// Copy all header fields.
	for key, values := range originalRequest.Header {
		for _, value := range values {
			pr.Header.Add(key, value)
		}
	}

	// Remove ignored header fields.
	for _, header := range ignoredHeaderNames {
		pr.Header.Del(header)
	}

	// Append this machine's host name into X-Forwarded-For.
	if requestHost, _, err := net.SplitHostPort(originalRequest.RemoteAddr); err == nil {
		if originalValues, ok := pr.Header["X-Forwarded-For"]; ok {
			requestHost = strings.Join(originalValues, ", ") + ", " + requestHost
		}
		pr.Header.Set("X-Forwarded-For", requestHost)
	}

	return pr
}
開發者ID:noonat,項目名稱:pruxy,代碼行數:34,代碼來源:proxy.go

示例15: copyRequest

func (f *Forwarder) copyRequest(req *http.Request, u *url.URL) *http.Request {
	outReq := new(http.Request)
	*outReq = *req // includes shallow copies of maps, but we handle this below

	outReq.URL = utils.CopyURL(req.URL)
	outReq.URL.Scheme = u.Scheme
	outReq.URL.Host = u.Host
	outReq.URL.Opaque = req.RequestURI
	// raw query is already included in RequestURI, so ignore it to avoid dupes
	outReq.URL.RawQuery = ""
	// Go doesn't implicitly pass the host header unless you set Host on the request
	outReq.Host = u.Host

	outReq.Proto = "HTTP/1.1"
	outReq.ProtoMajor = 1
	outReq.ProtoMinor = 1

	// Overwrite close flag so we can keep persistent connection for the backend servers
	outReq.Close = false

	outReq.Header = make(http.Header)
	utils.CopyHeaders(outReq.Header, req.Header)

	if f.rewriter != nil {
		f.rewriter.Rewrite(outReq)
	}
	return outReq
}
開發者ID:pasdoy,項目名稱:oxy,代碼行數:28,代碼來源:fwd.go


注:本文中的net/http.Request.Close方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。