// RouteHTTPToPath uses a reverse proxy to route the http request to the scheme, host provided in targetHost
// and path provided in targetPath.
968103
func RouteHTTPToPath(ctx jsonapi.InternalServerErrorContext, targetHost string, targetPath string) error {
	return route(ctx, targetHost, &targetPath)
}
1260792
func templateToSwaggerPath(path string) string {
	// It seems like the right thing to do here is to just use
	// strings.Split(path, "/") but that breaks badly when you hit a url like
	// /{my_field=prefix/*}/ and end up with 2 sections representing my_field.
	// Instead do the right thing and write a small pushdown (counter) automata
	// for it.
	var parts []string
	depth := 0
	buffer := ""
	for _, char := range path {
		switch char {
		case '{':
			// Push on the stack
			depth++
			buffer += string(char)
			break
		case '}':
			if depth == 0 {
				panic("Encountered } without matching { before it.")
			}
			// Pop from the stack
			depth--
			buffer += string(char)
		case '/':
			if depth == 0 {
				parts = append(parts, buffer)
				buffer = ""
				// Since the stack was empty when we hit the '/' we are done with this
				// section.
				continue
			}
			buffer += string(char)
		default:
			buffer += string(char)
			break
		}
	}

	// Now append the last element to parts
	parts = append(parts, buffer)

	// Parts is now an array of segments of the path. Interestingly, since the
	// syntax for this subsection CAN be handled by a regexp since it has no
	// memory.
	re := regexp.MustCompile("{([a-zA-Z][a-zA-Z0-9_.]*).*}")
	for index, part := range parts {
		// If part is a resource name such as "parent", "name", "user.name", the format info must be retained.
		prefix := re.ReplaceAllString(part, "$1")
		if isResourceName(prefix) {
			continue
		}
		parts[index] = re.ReplaceAllString(part, "{$1}")
	}

	return strings.Join(parts, "/")
}
1363131
func (rtr *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	rtr.serveHandler(rw, req)
}
373840
func (t *vhostTrie) splitHostPath(key string) (host, path string) {
	parts := strings.SplitN(key, "/", 2)
	host, path = strings.ToLower(parts[0]), "/"
	if len(parts) > 1 {
		path += parts[1]
	}
	// strip out the port (if present) from the host, since
	// each port has its own socket, and each socket has its
	// own listener, and each listener has its own server
	// instance, and each server instance has its own vhosts.
	// removing the port is a simple way to standardize so
	// when requests come in, we can be sure to get a match.
	hostname, _, err := net.SplitHostPort(host)
	if err == nil {
		host = hostname
	}
	return
}
405012
func encodeURL2Path(req *http.Request, virtualHost bool) (path string) {
	if virtualHost {
		reqHost := getHostAddr(req)
		dotPos := strings.Index(reqHost, ".")
		if dotPos > -1 {
			bucketName := reqHost[:dotPos]
			path = "/" + bucketName
			path += req.URL.Path
			path = s3utils.EncodePath(path)
			return
		}
	}
	path = s3utils.EncodePath(req.URL.Path)
	return
}
77382
func RewritePaths(next http.Handler, rewrites ...RewritePair) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		for _, rewrite := range rewrites {
			req.URL.Path = rewrite.Expr.ReplaceAllString(req.URL.Path, rewrite.Replacement)
		}
		next.ServeHTTP(w, req)
	})
}
954019
func OptionHostsPath(path string) SandboxOption {
	return func(sb *sandbox) {
		sb.config.hostsPath = path
	}
}
982147
func (r *Request) Path(path string) *Request {
	r.Use(url.Path(path))
	return r
}
663992
func (rd Redirect) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	for _, rule := range rd.Rules {
		if (rule.FromPath == "/" || r.URL.Path == rule.FromPath) && schemeMatches(rule, r) && rule.Match(r) {
			to := httpserver.NewReplacer(r, nil, "").Replace(rule.To)
			if rule.Meta {
				safeTo := html.EscapeString(to)
				fmt.Fprintf(w, metaRedir, safeTo, safeTo)
			} else {
				http.Redirect(w, r, to, rule.Code)
			}
			return 0, nil
		}
	}
	return rd.Next.ServeHTTP(w, r)
}
329102
func Convert_v1beta1_HTTPIngressPath_To_networking_HTTPIngressPath(in *v1beta1.HTTPIngressPath, out *networking.HTTPIngressPath, s conversion.Scope) error {
	return autoConvert_v1beta1_HTTPIngressPath_To_networking_HTTPIngressPath(in, out, s)
}
971844
func (c *Context) URLPath(ppath string, args ...map[string]interface{}) string {
	if len(ppath) == 0 {
		if len(c.ControllerName) > 0 {
			ppath = c.ControllerName + `/`
		}
		ppath += c.ActionName
		return c.Application.URLBuilder.BuildFromPath(c.Module.Name+`/`+ppath, args...)
	}
	ppath = strings.TrimLeft(ppath, `/`)
	return c.Application.URLBuilder.BuildFromPath(c.Module.Name+`/`+ppath, args...)
}
1084962
func RouteHTTP(ctx jsonapi.InternalServerErrorContext, target string) error {
	return route(ctx, target, nil)
}
511289
func routeToPage(c *router.Context) error {
	path := c.Params.ByName("path")
	switch chunks := strings.SplitN(path, "/+/", 2); {
	case len(chunks) <= 1: // no '/+/' in path => prefix listing page
		return prefixListingPage(c, path)
	case len(chunks) == 2 && chunks[1] == "": // ends with '/+/' => package page
		return packagePage(c, chunks[0])
	case len(chunks) == 2: // has something after '/+/' => instance page
		return instancePage(c, chunks[0], chunks[1])
	default:
		return status.Errorf(codes.InvalidArgument, "malformed page URL")
	}
}
1255875
func Path(path string) RequestOption {
	return func(req *http.Request) (*http.Request, error) {
		if req.URL != nil {
			u, err := req.URL.Parse(path)
			if err != nil {
				return nil, err
			}

			req.URL = u
			return req, nil
		}

		u, err := url.Parse(path)
		if err != nil {
			return nil, err
		}

		req.URL = u
		return req, nil
	}
}
160904
func (c *Context) TmplPath(args ...string) string {
	var app, ctl, act = c.App.Name, c.ControllerName, c.ActionName
	switch len(args) {
	case 3:
		app = args[2]
		fallthrough
	case 2:
		ctl = args[1]
		fallthrough
	case 1:
		act = args[0]
	}
	return app + `/` + ctl + `/` + act
}
1366603
func (r *RouteDefinition) FullPath() string {
	if r.IsAbsolute() {
		return httppath.Clean(r.Path[1:])
	}
	var base string
	if r.Parent != nil && r.Parent.Parent != nil {
		base = r.Parent.Parent.FullPath()
	}

	joinedPath := path.Join(base, r.Path)
	if strings.HasSuffix(r.Path, "/") {
		//add slash removed by Join back again (it may be important for routing)
		joinedPath += "/"
	}

	return httppath.Clean(joinedPath)
}
1128984
func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Recover from panic
	defer func() {
		if panicked := recover(); panicked != nil {
			// Generate a stack trace
			buf := make([]byte, 1<<16)

			// Set false to dump only this goroutine
			l := runtime.Stack(buf, false)
			log.Printf("%s\n\n%s", panicked, buf[:l])

			// TODO Only display an error in DEBUG
			http.Error(w, fmt.Sprintf("%s", panicked), 500)
		}
	}()

	// Build a new request and attach a user - if there is no valid user
	// the request.User will be an auth.AnonUser
	request := NewRequest(req, router.auth)

	// Record if a handler ran, so if false, a 404 page can be served
	var ranHandler bool
	var err error

	// Determine routes
	if root := router.trees[Method(req.Method)]; root != nil {
		path := req.URL.Path

		if h, ps, tsr := root.getValue(path); h != nil {
			// Add the parameters to the request
			request.Params = ps

			err = h(w, request)
			ranHandler = true
		} else if req.Method != "CONNECT" && path != "/" {
			code := 301 // Permanent redirect, request with GET method
			if req.Method != string(GET) {
				// Temporary redirect, request with same method
				// As of Go 1.3, Go does not support status code 308.
				code = 307
			}

			if tsr && router.RedirectTrailingSlash {
				if path[len(path)-1] == '/' {
					req.URL.Path = path[:len(path)-1]
				} else {
					req.URL.Path = path + "/"
				}
				http.Redirect(w, req, req.URL.String(), code)
				return
			}

			// Try to fix the request path
			if router.RedirectFixedPath {
				fixedPath, found := root.findCaseInsensitivePath(
					CleanPath(path),
					router.RedirectTrailingSlash,
				)
				if found {
					req.URL.Path = string(fixedPath)
					http.Redirect(w, req, req.URL.String(), code)
					return
				}
			}
		}
	}

	// Handle any other user errors
	// TODO Other codes?
	if err != nil {
		http.Error(w, err.Error(), 400)
		return
	}

	if ranHandler {
		return
	}
	http.NotFound(w, req)
}