cloudflare/pingora

Path rewriting utility function

Open

#462 opened on Nov 10, 2024

View on GitHub
 (0 comments) (1 reaction) (0 assignees)Rust (26,634 stars) (1,642 forks)batch import
enhancementergonomicshelp wanted

Description

What is the problem your feature solves, or the need it fulfills?

I am using pingora to proxy to other locally hosted web applications. These applications are hosted at a random port on localhost.

In order to forward the request to the appropriately the path needs to be rewritten.

Describe the solution you'd like

It would be nice if there was a method, associated function, function, etc, that simplified the process of path rewriting. For example when using caddy, the path is rewritten automagically. I suspect a method in pingora would ensure that rewriting is done correctly whereas I wouldn't put it past myself to do it incorrectly.

Describe alternatives you've considered

The following is the approach I am taking:

// helper function to get the first path then the rest of the request path
pub fn split_uri(uri: &Uri) -> (String, String) {
    let full_uri = uri.to_string();
    let splits = full_uri.split("/").skip(1).collect::<Vec<&str>>();
    let slug = format!("{}", splits[0..1].join("/"));
    let path = format!("/{}", splits[1..].join("/"));
    (slug, path)
}

// method implementation in the ProxyHttp trait
    // Optional but recommended method to modify requests before forwarding
    async fn upstream_request_filter(
        &self,
        session: &mut Session,
        request: &mut RequestHeader,
        _ctx: &mut Self::CTX,
    ) -> Result<()> {
        let path = request.uri.path();

        let (slug, path) = split_uri(&session.req_header().uri);

        // this check is only an example, in reality I am fetching from a DashMap
        if slug == "app" {
            request.set_uri(
                Uri::builder()
                    .path_and_query(PathAndQuery::from_str(&path).unwrap())
                    .build()
                    .unwrap(),
            );
        }
        Ok(())
    }

Additional context

It would be really great if pingora handled these headers in an automatic way so that some of the simplicity of other reverse proxies—e.g. caddy—could be found in pingora. That would give us (less web savvy users) an easier time focusing on the other fun stuff that pingora enables

Contributor guide