// Redirect redirects the request with status code.
426473
func (c *xContext) Redirect(url string, codes ...int) error {
	code := http.StatusFound
	if len(codes) > 0 {
		code = codes[0]
	}
	if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect {
		return ErrInvalidRedirectCode
	}
	err := c.preResponse()
	if err != nil {
		return err
	}
	format := c.Format()
	if format != `html` && c.auto {
		if render, ok := c.echo.formatRenderers[format]; ok && render != nil {
			if c.dataEngine.GetData() == nil {
				c.Set(`Location`, url)
				c.dataEngine.SetData(c.Stored(), c.dataEngine.GetCode().Int())
			} else {
				c.dataEngine.SetURL(url)
			}
			return render(c, c.dataEngine.GetData())
		}
	}
	c.response.Redirect(url, code)
	return nil
}
1328725
func (r *Router) Redirect(w http.ResponseWriter, req *http.Request, path string, code int) {
	http.Redirect(w, req, r.prefix+path, code)
}
1340441
func PreventRedirects(_ *http.Request, _ []*http.Request) error {
	return errors.New("redirects forbidden")
}
729637
func (c *Controller) Redirect(val interface{}, args ...interface{}) Result {
	c.setStatusIfNil(http.StatusFound)

	if url, ok := val.(string); ok {
		if len(args) == 0 {
			return &RedirectToURLResult{url}
		}
		return &RedirectToURLResult{fmt.Sprintf(url, args...)}
	}
	return &RedirectToActionResult{val, args}
}
525342
func (l4 L4PolicyMap) HasRedirect() bool {
	for _, f := range l4 {
		if f.IsRedirect() {
			return true
		}
	}

	return false
}
196909
func issueRedirect(urlPath string) (string, bool) {
	m := issueNum.FindStringSubmatch(urlPath)
	if m == nil {
		return "", false
	}
	issueNumber := strings.TrimPrefix(m[1], "/")
	suffix := ""
	if issueNumber != "" {
		suffix = "/" + issueNumber
	}
	return "https://github.com/perkeep/perkeep/issues" + suffix, true
}
959041
func prepareRedirect(options map[int]interface{}) (func(req *http.Request, via []*http.Request) error, error) {
	var redirectPolicy func(req *http.Request, via []*http.Request) error

	if redirectPolicy_, ok := options[OPT_REDIRECT_POLICY]; ok {
		if redirectPolicy, ok = redirectPolicy_.(func(*http.Request, []*http.Request) error); !ok {
			return nil, fmt.Errorf("OPT_REDIRECT_POLICY is not a desired function")
		}
	} else {
		var followlocation bool
		if followlocation_, ok := options[OPT_FOLLOWLOCATION]; ok {
			if followlocation, ok = followlocation_.(bool); !ok {
				return nil, fmt.Errorf("OPT_FOLLOWLOCATION must be bool")
			}
		}

		var maxredirs int
		if maxredirs_, ok := options[OPT_MAXREDIRS]; ok {
			if maxredirs, ok = maxredirs_.(int); !ok {
				return nil, fmt.Errorf("OPT_MAXREDIRS must be int")
			}
		}

		redirectPolicy = func(req *http.Request, via []*http.Request) error {
			// no follow
			if !followlocation || maxredirs <= 0 {
				return &Error{
					Code:    ERR_REDIRECT_POLICY,
					Message: fmt.Sprintf("redirect not allowed"),
				}
			}

			if len(via) >= maxredirs {
				return &Error{
					Code:    ERR_REDIRECT_POLICY,
					Message: fmt.Sprintf("stopped after %d redirects", len(via)),
				}
			}

			last := via[len(via)-1]
			// keep necessary headers
			// TODO: pass all headers or add other headers?
			if useragent := last.Header.Get("User-Agent"); useragent != "" {
				req.Header.Set("User-Agent", useragent)
			}

			return nil
		}
	}

	return redirectPolicy, nil
}
1080806
func RedirectToHandler(w http.ResponseWriter, r *http.Request) {
	u := mux.Vars(r)["url"]
	w.Header().Set("Location", u)
	w.WriteHeader(http.StatusFound)
}
56798
func (d *defaultClient) AuthedCheckRedirect(req *http.Request, via []*http.Request) error {
	if len(via) >= 10 {
		return errors.New("too many redirects")
	} else if len(via) == 0 {
		return nil
	}
	preserve := "Authorization"
	if auth, ok := via[0].Header[preserve]; ok {
		req.Header[preserve] = auth
	}
	d.Leader = req.URL.Host
	return nil
}
267108
func (a *admin) RedirectInfo() (params.RedirectInfoResult, error) {
	return params.RedirectInfoResult{}, fmt.Errorf("not redirected")
}
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)
}
679653
func Redirect(path string) FlatChains {
	return NewFlatChain(func(c *Context, nx NextHandler) {
		http.Redirect(c.Res, c.Req, path, http.StatusTemporaryRedirect)
		nx(c)
	}, nil)
}
1053911
func (m *Mixpanel) RedirectURL(distinctID, event, uri string, props Properties) (string, error) {
	if distinctID != "" {
		props["$distinct_id"] = distinctID
	}
	props["$token"] = m.Token
	props["mp_lib"] = library

	data := map[string]interface{}{"event": event, "properties": props}
	b, err := json.Marshal(data)
	if err != nil {
		return "", err
	}

	params := map[string]string{
		"data":     base64.StdEncoding.EncodeToString(b),
		"redirect": uri,
	}
	query := url.Values{}
	for k, v := range params {
		query[k] = []string{v}
	}
	return fmt.Sprintf("%s/%s?%s", m.BaseUrl, "track", query.Encode()), nil
}
332235
func RedirectHandler(client Client, op *OpenIDProvider, successfulAuthRedirectURL string) gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		authError := c.Query("error")
		if authError != "" {
			session.Delete("state")
			err := errors.Unauthorizedf("OP was unable to successfully authenticate your request: %s", authError)
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		serverState := c.Query("state")
		localState := session.Get("state")
		if localState == nil {
			err := errors.NotValidf("Couldn't find the local state or nonce to verify the response from the OP")
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		if localState.(string) != serverState {
			c.String(http.StatusForbidden, "Nonce or state did not match")
			c.Abort()
		}

		code := c.Query("code")
		token, err := op.Exchange(code, client)
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		session.Set("OpenIDTokenResponse", token)
		ui, err := op.UserInfo(token.AccessToken)
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		session.Set("UserInfo", ui)
		session.Delete("nonce")
		err = session.Save()
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
		}
		c.Redirect(http.StatusFound, successfulAuthRedirectURL)
	}
}
711277
func (s *RoutingRule) SetRedirect(v *Redirect) *RoutingRule {
	s.Redirect = v
	return s
}
415603
func (r *Response) SetRedirect(url string) {
	// set redirect parameters
	r.Type = REDIRECT
	r.URL = url
}
1046149
func (p *Proxy) removeRedirect(id string, wg *completion.WaitGroup) (err error, finalizeFunc revert.FinalizeFunc, revertFunc revert.RevertFunc) {
	log.WithField(fieldProxyRedirectID, id).
		Debug("Removing proxy redirect")

	r, ok := p.redirects[id]
	if !ok {
		return fmt.Errorf("unable to find redirect %s", id), nil, nil
	}
	delete(p.redirects, id)

	implFinalizeFunc, implRevertFunc := r.implementation.Close(wg)

	// Delay the release and reuse of the port number so it is guaranteed to be
	// safe to listen on the port again. This can't be reverted, so do it in a
	// FinalizeFunc.
	proxyPort := r.listener.proxyPort
	listenerName := r.listener.name

	finalizeFunc = func() {
		// break GC loop (implementation may point back to 'r')
		r.implementation = nil

		if implFinalizeFunc != nil {
			implFinalizeFunc()
		}

		go func() {
			time.Sleep(portReuseDelay)

			proxyPortsMutex.Lock()
			err := p.releaseProxyPort(listenerName)
			proxyPortsMutex.Unlock()
			if err != nil {
				log.WithField(fieldProxyRedirectID, id).WithError(err).Warningf("Releasing proxy port %d failed", proxyPort)
			}
		}()
	}

	revertFunc = func() error {
		if implRevertFunc != nil {
			return implRevertFunc()
		}

		p.mutex.Lock()
		p.redirects[id] = r
		p.mutex.Unlock()

		return nil
	}

	return
}