Golang Request.Host Examples

Golang Request.Host - 30 examples found. These are the top rated real world Golang examples of net/http.Request.Host extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
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
}
Example #2
0
File: utils.go Project: shtlee/qa
// 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
}
Example #3
0
// 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
}
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
}
Example #5
0
File: fwd.go Project: narma/oxy
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
}
Example #6
0
// 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)
	}
}