本文整理汇总了Golang中net/http.Request.Proto方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.Proto方法的具体用法?Golang Request.Proto怎么用?Golang Request.Proto使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Request
的用法示例。
在下文中一共展示了Request.Proto方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Proxy
func (p *WebsocketProxy) Proxy(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
log.Println("hijack assertion failed", r.Host, r.URL.Path)
p.handler.ServeHTTP(w, r) // last-ditch effort as plain http
return
}
conn, rw, err := hj.Hijack()
if err != nil {
log.Println("hijack failed", r.Host, r.URL.Path, err)
p.handler.ServeHTTP(w, r) // last-ditch effort as plain http
return
}
defer conn.Close()
rw.Flush()
wrapreq := new(http.Request)
wrapreq.Proto = "HTTP/1.1"
wrapreq.ProtoMajor, wrapreq.ProtoMinor = 1, 1
wrapreq.Method = "WEBSOCKET"
wrapreq.Host = r.Host
const dummy = "/"
wrapreq.URL = &url.URL{Path: dummy}
var buf bytes.Buffer
r.Write(&buf)
wrapreq.Body = ioutil.NopCloser(io.MultiReader(&buf, conn))
resp, err := p.transport.RoundTrip(wrapreq)
if err != nil || resp.StatusCode != 200 {
io.WriteString(conn, "HTTP/1.0 503 Gateway Failed\r\n")
io.WriteString(conn, "Connection: close\r\n\r\n")
return
}
defer resp.Body.Close()
io.Copy(conn, resp.Body)
}
示例2: 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
}
示例3: 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
}
示例4: 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
}
示例5: 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
}
示例6: 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
}
示例7: RoundTrip
// RoundTrip implements http.RoundTripper.RoundTrip.
func (binder Binder) RoundTrip(req *http.Request) (*http.Response, error) {
if req.Proto == "" {
req.Proto = fmt.Sprintf("HTTP/%d.%d", req.ProtoMajor, req.ProtoMinor)
}
if req.Body != nil {
if req.ContentLength == -1 {
req.TransferEncoding = []string{"chunked"}
}
} else {
req.Body = ioutil.NopCloser(bytes.NewReader(nil))
}
recorder := httptest.NewRecorder()
binder.handler.ServeHTTP(recorder, req)
resp := http.Response{
Request: req,
StatusCode: recorder.Code,
Status: http.StatusText(recorder.Code),
Header: recorder.HeaderMap,
}
if recorder.Flushed {
resp.TransferEncoding = []string{"chunked"}
}
if recorder.Body != nil {
resp.Body = ioutil.NopCloser(recorder.Body)
}
return &resp, nil
}
示例8: copyRequest
func (l *HttpLocation) copyRequest(req *http.Request, body netutils.MultiReader, endpoint endpoint.Endpoint) *http.Request {
outReq := new(http.Request)
*outReq = *req // includes shallow copies of maps, but we handle this below
// Set the body to the enhanced body that can be re-read multiple times and buffered to disk
outReq.Body = body
endpointURL := endpoint.GetUrl()
outReq.URL.Scheme = endpointURL.Scheme
outReq.URL.Host = endpointURL.Host
outReq.URL.Opaque = req.RequestURI
// raw query is already included in RequestURI, so ignore it to avoid dupes
outReq.URL.RawQuery = ""
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)
netutils.CopyHeaders(outReq.Header, req.Header)
return outReq
}
示例9: NewFastHTTPHandler
// NewFastHTTPHandler wraps net/http handler to fasthttp request handler,
// so it can be passed to fasthttp server.
//
// While this function may be used for easy switching from net/http to fasthttp,
// it has the following drawbacks comparing to using manually written fasthttp
// request handler:
//
// * A lot of useful functionality provided by fasthttp is missing
// from net/http handler.
// * net/http -> fasthttp handler conversion has some overhead,
// so the returned handler will be always slower than manually written
// fasthttp handler.
//
// So it is advisable using this function only for quick net/http -> fasthttp
// switching. Then manually convert net/http handlers to fasthttp handlers
// according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .
func NewFastHTTPHandler(h http.Handler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
var r http.Request
body := ctx.PostBody()
r.Method = string(ctx.Method())
r.Proto = "HTTP/1.1"
r.ProtoMajor = 1
r.ProtoMinor = 1
r.RequestURI = string(ctx.RequestURI())
r.ContentLength = int64(len(body))
r.Host = string(ctx.Host())
r.RemoteAddr = ctx.RemoteAddr().String()
hdr := make(http.Header)
ctx.Request.Header.VisitAll(func(k, v []byte) {
hdr.Set(string(k), string(v))
})
r.Header = hdr
r.Body = &netHTTPBody{body}
var w netHTTPResponseWriter
h.ServeHTTP(&w, &r)
ctx.SetStatusCode(w.StatusCode())
for k, vv := range w.Header() {
for _, v := range vv {
ctx.Response.Header.Set(k, v)
}
}
ctx.Write(w.body)
}
}
示例10: ServeHTTP
func (p *ReverseProxy) ServeHTTP(req *http.Request) (*http.Response, error) {
transport := p.Transport
if transport == nil {
transport = http.DefaultTransport
}
outreq := new(http.Request)
*outreq = *req // includes shallow copies of maps, but okay
p.Director(outreq)
outreq.Proto = "HTTP/1.1"
outreq.ProtoMajor = 1
outreq.ProtoMinor = 1
outreq.Close = false
// 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. This
// is modifying the same underlying map from req (shallow
// copied above) so we only copy it if necessary.
copiedHeaders := false
for _, h := range hopHeaders {
if outreq.Header.Get(h) != "" {
if !copiedHeaders {
outreq.Header = make(http.Header)
copyHeader(outreq.Header, req.Header)
copiedHeaders = true
}
outreq.Header.Del(h)
}
}
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
// If we aren't the first proxy retain prior
// X-Forwarded-For information as a comma+space
// separated list and fold multiple headers into one.
if prior, ok := outreq.Header["X-Forwarded-For"]; ok {
clientIP = strings.Join(prior, ", ") + ", " + clientIP
}
outreq.Header.Set("X-Forwarded-For", clientIP)
}
res, err := transport.RoundTrip(outreq)
if err != nil {
return res, err
}
for _, p := range *p.Plugins {
p.Outbound(res)
}
for _, h := range hopHeaders {
res.Header.Del(h)
}
return res, nil
}
示例11: makeRequest
func makeRequest(params map[string]string) (*http.Request, error) {
r := new(http.Request)
r.Method = params["METHOD"]
if r.Method == "" {
return nil, errors.New("mongrel2: no METHOD")
}
r.Proto = params["VERSION"]
var ok bool
r.ProtoMajor, r.ProtoMinor, ok = http.ParseHTTPVersion(r.Proto)
if !ok {
return nil, errors.New("mongrel2: invalid protocol version")
}
r.Trailer = http.Header{}
r.Header = http.Header{}
r.Host = params["Host"]
r.Header.Set("Referer", params["Referer"])
r.Header.Set("User-Agent", params["User-Agent"])
if lenstr := params["Content-Length"]; lenstr != "" {
clen, err := strconv.ParseInt(lenstr, 10, 64)
if err != nil {
return nil, errors.New("mongrel2: bad Content-Length")
}
r.ContentLength = clen
}
for k, v := range params {
if !skipHeader[k] {
r.Header.Add(k, v)
}
}
// TODO: cookies
if r.Host != "" {
url_, err := url.Parse("http://" + r.Host + params["URI"])
if err != nil {
return nil, errors.New("mongrel2: failed to parse host and URI into a URL")
}
r.URL = url_
}
if r.URL == nil {
url_, err := url.Parse(params["URI"])
if err != nil {
return nil, errors.New("mongrel2: failed to parse URI into a URL")
}
r.URL = url_
}
// TODO: how do we know if we're using HTTPS?
// TODO: fill in r.RemoteAddr
return r, nil
}
示例12: ServeHTTP
func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, outreq *http.Request, respUpdateFn respUpdateFn) error {
transport := p.Transport
if transport == nil {
transport = http.DefaultTransport
}
p.Director(outreq)
outreq.Proto = "HTTP/1.1"
outreq.ProtoMajor = 1
outreq.ProtoMinor = 1
outreq.Close = false
res, err := transport.RoundTrip(outreq)
if err != nil {
return err
} else if respUpdateFn != nil {
respUpdateFn(res)
}
if res.StatusCode == http.StatusSwitchingProtocols && strings.ToLower(res.Header.Get("Upgrade")) == "websocket" {
res.Body.Close()
hj, ok := rw.(http.Hijacker)
if !ok {
return nil
}
conn, _, err := hj.Hijack()
if err != nil {
return err
}
defer conn.Close()
backendConn, err := net.Dial("tcp", outreq.URL.Host)
if err != nil {
return err
}
defer backendConn.Close()
outreq.Write(backendConn)
go func() {
io.Copy(backendConn, conn) // write tcp stream to backend.
}()
io.Copy(conn, backendConn) // read tcp stream from backend.
} else {
defer res.Body.Close()
for _, h := range hopHeaders {
res.Header.Del(h)
}
copyHeader(rw.Header(), res.Header)
rw.WriteHeader(res.StatusCode)
p.copyResponse(rw, res.Body)
}
return nil
}
示例13: prepareRequest
func prepareRequest(req *http.Request) *http.Request {
outreq := new(http.Request)
*outreq = *req // includes shallow copies of maps, but okay
// Pass the Request-URI verbatim without any modifications.
//
// NOTE: An exception must be made if the Request-URI is a path
// beginning with "//" (e.g. "//foo/bar") because then
// req.URL.RequestURI() would interpret req.URL.Opaque as being a URI
// with the scheme stripped and so generate a URI like scheme:opaque
// (e.g. "http://foo/bar") which would be incorrect, see:
// https://github.com/golang/go/blob/f75aafd/src/net/url/url.go#L913-L931
//
// It is ok to make this exception because the fallback to
// req.URL.EscapedPath will generate the correct Request-URI.
if !strings.HasPrefix(req.RequestURI, "//") {
outreq.URL.Opaque = strings.Split(strings.TrimPrefix(req.RequestURI, req.URL.Scheme+":"), "?")[0]
}
outreq.URL.Scheme = "http"
outreq.Proto = "HTTP/1.1"
outreq.ProtoMajor = 1
outreq.ProtoMinor = 1
outreq.Close = false
// Remove hop-by-hop headers to the backend.
outreq.Header = make(http.Header)
copyHeader(outreq.Header, req.Header)
for _, h := range hopHeaders {
outreq.Header.Del(h)
}
// remove the Upgrade header and headers referenced in the Connection
// header if HTTP < 1.1 or if Connection header didn't contain "upgrade":
// https://tools.ietf.org/html/rfc7230#section-6.7
if !req.ProtoAtLeast(1, 1) || !isConnectionUpgrade(req.Header) {
outreq.Header.Del("Upgrade")
// Especially important is "Connection" because we want a persistent
// connection, regardless of what the client sent to us.
outreq.Header.Del("Connection")
// A proxy or gateway MUST parse a received Connection header field before a
// message is forwarded and, for each connection-option in this field, remove
// any header field(s) from the message with the same name as the
// connection-option, and then remove the Connection header field itself (or
// replace it with the intermediary's own connection options for the
// forwarded message): https://tools.ietf.org/html/rfc7230#section-6.1
tokens := strings.Split(req.Header.Get("Connection"), ",")
for _, hdr := range tokens {
outreq.Header.Del(hdr)
}
}
return outreq
}
示例14: reverseProxy
func reverseProxy(w http.ResponseWriter, req *http.Request) {
logRequest(req)
if rSensitivePath.MatchString(req.URL.Path) {
w.WriteHeader(http.StatusForbidden)
return
}
outReq := new(http.Request)
outReq.Method = req.Method
outReq.URL = &url.URL{
Scheme: "http",
Host: host,
Path: req.URL.Path,
RawQuery: req.URL.RawQuery,
}
outReq.Proto = "HTTP/1.1"
outReq.ProtoMajor = 1
outReq.ProtoMinor = 1
outReq.Header = make(http.Header)
outReq.Body = req.Body
outReq.ContentLength = req.ContentLength
outReq.Host = host
for _, h := range removeHeaders {
req.Header.Del(h)
}
copyHeader(outReq.Header, req.Header)
outReq.Header.Set("Host", host)
outReq.Header.Set("Referer", baseURL)
outReq.Header.Set("Origin", baseURL)
resp, err := send(outReq)
if err != nil {
log.Printf("proxy error: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer resp.Body.Close()
for _, h := range removeHeaders {
resp.Header.Del(h)
}
if loc := resp.Header.Get("Location"); loc != "" {
if u, err := url.Parse(loc); err == nil && u.Host == host {
u.Scheme = "http"
u.Host = req.Host
resp.Header.Set("Location", u.String())
}
}
copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
示例15: ServeHTTP
func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, location string) {
transport := p.Transport
if transport == nil {
transport = http.DefaultTransport
}
outreq := new(http.Request)
p.Director(outreq)
outreq.Proto = "HTTP/1.1"
outreq.ProtoMajor = 1
outreq.ProtoMinor = 1
outreq.Close = false
// 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. This
// is modifying the same underlying map from req (shallow
// copied above) so we only copy it if necessary.
copiedHeaders := false
for _, h := range hopHeaders {
if outreq.Header.Get(h) != "" {
if !copiedHeaders {
outreq.Header = make(http.Header)
copyHeader(outreq.Header, req.Header)
copiedHeaders = true
}
outreq.Header.Del(h)
}
}
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
// If we aren't the first proxy retain prior
// X-Forwarded-For information as a comma+space
// separated list and fold multiple headers into one.
if prior, ok := outreq.Header["X-Forwarded-For"]; ok {
clientIP = strings.Join(prior, ", ") + ", " + clientIP
}
outreq.Header.Set("X-Forwarded-For", clientIP)
}
res, err := transport.RoundTrip(outreq)
if err != nil {
log.Printf("http: proxy error: %v", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
defer res.Body.Close()
copyHeader(rw.Header(), res.Header)
rw.WriteHeader(res.StatusCode)
p.copyResponse(rw, res.Body)
}