本文整理汇总了Golang中net/http.Request.Host方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.Host方法的具体用法?Golang Request.Host怎么用?Golang Request.Host使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Request
的用法示例。
在下文中一共展示了Request.Host方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: serveProgressHtml
func serveProgressHtml(backend backend, w http.ResponseWriter, req *http.Request) bool {
// Only do this for modern browsers.
useragent := req.Header.Get("User-Agent")
if !strings.Contains(useragent, "Mozilla") || isWebsocket(req) {
return false
}
// TODO: Not for images and those kind of stuff?
// Only show when we're provisioning
if backend.IsReady() {
return false
}
info := backend.GetInfo()
// Okey, we're the ones sending the data.
w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Add("Pragma", "no-cache")
w.Header().Add("Expires", "0")
// Serve custom progress file?
if info.ProgressPage != nil && info.ProgressPage.Filename != "" {
http.ServeFile(w, req, info.ProgressPage.Filename)
} else if info.ProgressPage != nil && info.ProgressPage.Url != "" {
director := func(req *http.Request) {
req.URL, _ = url.Parse(info.ProgressPage.Url)
req.Host = req.URL.Host
if info.ProgressPage.Hostname != "" {
req.Host = info.ProgressPage.Hostname
}
}
proxy := &httputil.ReverseProxy{Director: director}
proxy.ServeHTTP(w, req)
} else {
templateVars := make(map[string]string)
templateVars["BackgroundColor"] = "#41964B"
if info.ProgressPage != nil && info.ProgressPage.Style != nil {
if info.ProgressPage.Style.BackgroundColor != "" {
templateVars["BackgroundColor"] = info.ProgressPage.Style.BackgroundColor
}
}
tmpl, err := template.New("test").Parse(contents)
if err != nil {
log.Panicf("Failed to parse template: %v", err)
}
err = tmpl.Execute(w, templateVars)
if err != nil {
io.WriteString(w, "Failed to render template")
}
}
return true
}
示例2: DoHttpGetEx
// use specified ip and host
func DoHttpGetEx(host, ip, url string) (b *bytes.Buffer, err error) {
var (
req *http.Request
resp *http.Response
)
lastIdx := strings.LastIndex(ip, ":")
if lastIdx == strings.Index(ip, ":") {
lastIdx = len(ip)
}
ip2 := string([]byte(ip[7:lastIdx]))
url2 := replaceHostWithIP(url, host, ip2)
if req, err = http.NewRequest("GET", url2, nil); err != nil {
return
}
req.Host = host
if resp, err = http.DefaultClient.Do(req); err != nil {
return
}
defer resp.Body.Close()
b = new(bytes.Buffer)
io.Copy(b, resp.Body)
return
}
示例3: do
// do an HTTP request to a server and returns the response object and the
// complete response body. There's no need to close the response body as this
// will have been done.
func do(method, req_body, host, ua, uri string, extraHeaders map[string]string) (*http.Response, []byte, error) {
var err error
var req *http.Request
if strings.EqualFold("POST", method) || strings.EqualFold("PUT", method) {
req, err = http.NewRequest(method, uri, strings.NewReader(req_body))
} else {
req, err = http.NewRequest(method, uri, nil)
}
if err != nil {
return nil, nil, err
}
if host != "" {
req.Host = host
}
if ua != "" {
req.Header["User-Agent"] = []string{ua}
}
for k, v := range extraHeaders {
req.Header.Add(k, v)
}
resp, err := transport.RoundTrip(req)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return resp, nil, err
}
body, err := ioutil.ReadAll(resp.Body)
return resp, body, err
}
示例4: ServeHTTP
func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
transport := new(http.Transport)
h, ok := w.(http.Hijacker)
if !ok {
return errors.New("Unable to hijack connection")
}
r.Host = srv.addr
r.URL.Host = r.Host
if len(r.URL.Scheme) == 0 {
r.URL.Scheme = "http"
}
response, err := transport.RoundTrip(r)
if err != nil {
return err
}
conn, _, err := h.Hijack()
if err != nil {
return err
}
defer conn.Close()
defer response.Body.Close()
return response.Write(conn)
}
示例5: forwardRequest
func forwardRequest(r *http.Request, ip string, destport int, client http.Client, requesturl string, responseChannel chan int, wg *sync.WaitGroup) {
defer wg.Done()
r.Host = ip
r.RequestURI = ""
newURL, err := url.Parse(fmt.Sprintf("http://%v:%d%v", ip, destport, requesturl))
if err != nil {
log.Printf("Error parsing URL: %s\n", err)
if *debug {
log.Printf("For URL: %s\n", fmt.Sprintf("http://%v:%d%v", ip, destport, requesturl))
}
responseChannel <- 500
return
}
r.URL = newURL
response, err := client.Do(r)
if err != nil {
log.Printf("Error sending request: %s\n", err)
if *debug {
log.Printf("For URL: %s\n", r.URL)
}
responseChannel <- 500
return
}
io.Copy(ioutil.Discard, response.Body)
defer response.Body.Close()
return
}
示例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
// 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
}
示例7: 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)
}
}
示例8: revertOriginalHost
// This filthy hack works in conjunction with hostPortStrip to restore the
// original request host after mux match.
func revertOriginalHost(r *http.Request) {
original := r.Header.Get("_devd_original_host")
if original != "" {
r.Host = original
r.Header.Del("_devd_original_host")
}
}
示例9: 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)
}
示例10: ApplyAuthentication
// Sets the Authorization header on the request to use the provided token.
// Will also re-write the host value of the request URL to use the value
// provided in the TokenAuth.
func (a TokenAuth) ApplyAuthentication(r *http.Request) {
token := fmt.Sprintf("Token %s", a.Token)
r.Header.Add("Authorization", token)
r.URL.Host = a.Host
r.Host = a.Host
}
示例11: DoWithLoadBalancer
func (lb *BackendLoadBalancer) DoWithLoadBalancer(req *http.Request, useTLS bool) (*http.Response, error) {
connectString, err := lb.LoadBalancer.GetConnectAddress()
if err != nil {
return nil, err
}
log.Debug("connect string is ", connectString)
req.URL.Host = connectString
req.Host = connectString
var transport *http.Transport
if useTLS == true {
log.Debug("Configuring TLS transport")
transport = lb.httpsTransport
req.URL.Scheme = "https"
} else {
log.Debug("Configuring non-TLS transport")
transport = lb.httpTransport
req.URL.Scheme = "http"
}
client := &http.Client{
Transport: transport,
}
req.RequestURI = "" //Must clear when using http.Client
return ctxhttp.Do(req.Context(), client, req)
}
示例12: ServeHTTP
// ServeHTTP handles the response
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if ProxyPath != "" && strings.HasPrefix(req.URL.Path, "/"+ProxyPath) {
uri, err := url.Parse(req.FormValue("uri"))
if err != nil {
s.debug.Println(req.RequestURI, err.Error())
}
req.URL = uri
req.Host = uri.Host
req.RequestURI = uri.RequestURI()
proxy.ServeHTTP(w, req)
return
}
if websocketUpgrade(req) {
websocketServe(w, req)
return
}
defer func() {
req.Body.Close()
}()
r := s.handle(w, &httpRequest{req, s})
for key := range r.headers {
w.Header().Set(key, r.headers.Get(key))
}
if r.status > 0 {
w.WriteHeader(r.status)
}
if len(r.argv) > 0 {
fmt.Fprint(w, r.argv...)
}
}
示例13: 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
}
示例14: Director
// Director is required by the proxy; it rewrites the URL
// before the proxy operates
func (p S3ReverseProxy) Director(req *http.Request) {
// we need to rewrite the URL but also S3 insists on having
// the host and requesturi correct.
p.RewriteUrl(req.URL)
req.RequestURI = req.URL.Path
req.Host = req.URL.Host
}
示例15: proxyHTTP
// proxyHTTP will proxy the http.Request r to the new hos
// This does modify r in the process of proxying the request
func (self *Proxy) proxyHTTP(w http.ResponseWriter, r *http.Request) {
r.Header.Add("X-Forwarded-Host", r.Host)
r.Header.Add("X-Forwarded-For", r.RemoteAddr)
r.Host = self.Target
r.URL.Host = self.Target
// Reset Request properteis for Client
r.URL.Scheme = "http"
r.RequestURI = ""
resp, err := self.Client.Do(r)
if err != nil {
http.Error(w, BAD_GATEWAY, http.StatusBadGateway)
return
}
// Copy response header
for key, _ := range resp.Header {
w.Header().Set(key, resp.Header.Get(key))
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}