本文整理汇总了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)
}
示例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
}
}
示例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)
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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
}