// checkHTTPRedirect is a callback that can manipulate redirected HTTP
// requests. It is used to preserve Accept and Range headers.
333790
func checkHTTPRedirect(req *http.Request, via []*http.Request) error {
	if len(via) >= 10 {
		return errors.New("stopped after 10 redirects")
	}

	if len(via) > 0 {
		for headerName, headerVals := range via[0].Header {
			if headerName != "Accept" && headerName != "Range" {
				continue
			}
			for _, val := range headerVals {
				// Don't add to redirected request if redirected
				// request already has a header with the same
				// name and value.
				hasValue := false
				for _, existingVal := range req.Header[headerName] {
					if existingVal == val {
						hasValue = true
						break
					}
				}
				if !hasValue {
					req.Header.Add(headerName, val)
				}
			}
		}
	}

	return nil
}
335788
func PermanentRedirect(w http.ResponseWriter, response interface{}) {
	Respond(w, http.StatusPermanentRedirect, response)
}
1340441
func PreventRedirects(_ *http.Request, _ []*http.Request) error {
	return errors.New("redirects forbidden")
}
1052533
func (user *User) OauthRedirectURL() string {
	providerID := user.ctx.OAuthProvider().internalID()
	if providerID == user.ctx.ServiceName {
		return fmt.Sprintf("%s/auth/%s", Config.BaseURL, user.ctx.ServiceName)
	}

	return fmt.Sprintf("%s/auth/%s/%s", Config.BaseURL, user.ctx.ServiceName, providerID)
}
172116
func (h *HTTPBin) RedirectTo(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()

	url := q.Get("url")
	if url == "" {
		http.Error(w, "Missing URL", http.StatusBadRequest)
		return
	}

	var err error
	statusCode := http.StatusFound
	rawStatusCode := q.Get("status_code")
	if rawStatusCode != "" {
		statusCode, err = strconv.Atoi(q.Get("status_code"))
		if err != nil || statusCode < 300 || statusCode > 399 {
			http.Error(w, "Invalid status code", http.StatusBadRequest)
			return
		}
	}

	w.Header().Set("Location", url)
	w.WriteHeader(statusCode)
}
507330
func (c *ServerCommand) detectRedirect(detect physical.RedirectDetect,
	config *server.Config) (string, error) {
	// Get the hostname
	host, err := detect.DetectHostAddr()
	if err != nil {
		return "", err
	}

	// set [] for ipv6 addresses
	if strings.Contains(host, ":") && !strings.Contains(host, "]") {
		host = "[" + host + "]"
	}

	// Default the port and scheme
	scheme := "https"
	port := 8200

	// Attempt to detect overrides
	for _, list := range config.Listeners {
		// Only attempt TCP
		if list.Type != "tcp" {
			continue
		}

		// Check if TLS is disabled
		if val, ok := list.Config["tls_disable"]; ok {
			disable, err := parseutil.ParseBool(val)
			if err != nil {
				return "", errwrap.Wrapf("tls_disable: {{err}}", err)
			}

			if disable {
				scheme = "http"
			}
		}

		// Check for address override
		var addr string
		addrRaw, ok := list.Config["address"]
		if !ok {
			addr = "127.0.0.1:8200"
		} else {
			addr = addrRaw.(string)
		}

		// Check for localhost
		hostStr, portStr, err := net.SplitHostPort(addr)
		if err != nil {
			continue
		}
		if hostStr == "127.0.0.1" {
			host = hostStr
		}

		// Check for custom port
		listPort, err := strconv.Atoi(portStr)
		if err != nil {
			continue
		}
		port = listPort
	}

	// Build a URL
	url := &url.URL{
		Scheme: scheme,
		Host:   fmt.Sprintf("%s:%d", host, port),
	}

	// Return the URL string
	return url.String(), nil
}
1338180
func (self *GoogleProvider) Redirect(w http.ResponseWriter, r *http.Request) {
	const scope = "https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email"
	self.OAuth2Mixin.AuthorizeRedirect(w, r, scope)
}
275663
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Get the URL path.
	path := r.URL.Path

	// Call this in an inline function to handle errors.
	statusCode, err := func() (int, error) {
		// Check the origin.
		if !s.checkOriginFunc(r) {
			return http.StatusForbidden, fmt.Errorf("origin not allowed")
		}

		// Set the required HTTP headers for cross origin requests if enabled.
		if s.enableCORS {
			// Parse the origin url.
			origin := r.Header["Origin"]
			if len(origin) == 0 || len(origin[0]) == 0 {
				return 400, fmt.Errorf("failed to set header: Access-Control-Allow-Origin: HTTP request origin header is empty")
			}

			w.Header().Set("Access-Control-Allow-Origin", origin[0])   // Set allowed origin.
			w.Header().Set("Access-Control-Allow-Methods", "POST,GET") // Only allow POST and GET requests.
		}

		// Strip the base URL.
		if len(path) < s.httpURLStripLength {
			return http.StatusBadRequest, fmt.Errorf("invalid request")
		}
		path = path[s.httpURLStripLength:]

		// Route the HTTP request in a very simple way by comparing the strings.
		if path == httpURLWebSocketSuffix {
			// Handle the websocket request.
			s.webSocketServer.HandleRequest(w, r)
		} else if path == httpURLAjaxSocketSuffix {
			// Handle the ajax request.
			s.ajaxSocketServer.HandleRequest(w, r)
		} else {
			return http.StatusBadRequest, fmt.Errorf("invalid request")
		}

		return http.StatusAccepted, nil
	}()

	// Handle the error.
	if err != nil {
		// Set the HTTP status code.
		w.WriteHeader(statusCode)

		// Get the remote address and user agent.
		remoteAddr, _ := utils.RemoteAddress(r)
		userAgent := r.Header.Get("User-Agent")

		// Log the invalid request.
		log.L.WithFields(logrus.Fields{
			"remoteAddress": remoteAddr,
			"userAgent":     userAgent,
			"url":           r.URL.Path,
		}).Warningf("handle HTTP request: %v", err)
	}
}
711277
func (s *RoutingRule) SetRedirect(v *Redirect) *RoutingRule {
	s.Redirect = v
	return s
}
414115
func (c *OAuthAccessCall) RedirectURI(redirectURI string) *OAuthAccessCall {
	c.redirectURI = redirectURI
	return c
}
929189
func (self *Param) checkRedirect(req *http.Request, via []*http.Request) error {
	if self.redirectTimes == 0 {
		return nil
	}
	if len(via) >= self.redirectTimes {
		if self.redirectTimes < 0 {
			return fmt.Errorf("not allow redirects.")
		}
		return fmt.Errorf("stopped after %v redirects.", self.redirectTimes)
	}
	return nil
}
413170
func (req *AuthnRequest) Redirect(relayState string) *url.URL {
	w := &bytes.Buffer{}
	w1 := base64.NewEncoder(base64.StdEncoding, w)
	w2, _ := flate.NewWriter(w1, 9)
	doc := etree.NewDocument()
	doc.SetRoot(req.Element())
	if _, err := doc.WriteTo(w2); err != nil {
		panic(err)
	}
	w2.Close()
	w1.Close()

	rv, _ := url.Parse(req.Destination)

	query := rv.Query()
	query.Set("SAMLRequest", string(w.Bytes()))
	if relayState != "" {
		query.Set("RelayState", relayState)
	}
	rv.RawQuery = query.Encode()

	return rv
}
300534
func (c *Client) DoRequestWithoutRedirects(r *Request) (*http.Response, error) {
	prevCheckRedirect := c.Config.HttpClient.CheckRedirect
	c.Config.HttpClient.CheckRedirect = func(httpReq *http.Request, via []*http.Request) error {
		return http.ErrUseLastResponse
	}
	defer func() {
		c.Config.HttpClient.CheckRedirect = prevCheckRedirect
	}()
	return c.DoRequest(r)
}
69523
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Check if a http.Handler is registered for the given host.
	// If yes, use it to handle the request.
	if handler := hs[r.Host]; handler != nil {
		handler.ServeHTTP(w, r)
	} else {
		// Handle host names for wich no handler is registered
		http.Error(w, "Forbidden", 403) // Or Redirect?
	}
}
1080806
func RedirectToHandler(w http.ResponseWriter, r *http.Request) {
	u := mux.Vars(r)["url"]
	w.Header().Set("Location", u)
	w.WriteHeader(http.StatusFound)
}
1328725
func (r *Router) Redirect(w http.ResponseWriter, req *http.Request, path string, code int) {
	http.Redirect(w, req, r.prefix+path, code)
}
364374
func (ctx *Context) Redirect(status int, url_ string) {
	ctx.ResponseWriter.Header().Set("Location", url_)
	ctx.ResponseWriter.WriteHeader(status)
	ctx.ResponseWriter.Write([]byte("Redirecting to: " + url_))
}