Hacktoberfest 2026: as issues que os mantenedores marcaram para outubro, abertas e boas para iniciantes. Ver issues do Hacktoberfest

Cannot change path of Uri with less than two failure branches

Aberta
#594 3 comentários 2 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
5/5
Tempo estimado
Mais de uma semana
Facilidade para iniciantes
35/100
Tipo de issue
Funcionalidade
Clareza
Razoavelmente clara
Status de atividade
Estagnada
Stack de tecnologia
rust
Domínio
api

Direção de pesquisa

Comece lendo as APIs existentes http::uri::Builder, Uri::into_parts, Parts e path_and_query descritas na issue. Compare os designs propostos para from_uri e from_parts e, em seguida, determine qual preserva o modelo de erros existente e é consistente com a API de builder. Considera-se concluído quando houver um design de API acordado e revisado, não uma implementação baseada em uma alternativa não resolvida.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

I have a many scenarios where I have one Uri and want to change its path_and_query, but this doesn't seem possible without writing code that can yield at least two distinct errors.

This doesn't make sense; realistically, only one error can occur: that the path_and_query is invalid. Beyond that, the operation should be infallible.

Here's one approach that I tried:

    // self.base_url is of type `Uri`
    pub fn relative_uri(&self, path: &str) -> Result<Uri, XXX> {
        let mut parts = self.base_url.clone().into_parts();
        parts.path_and_query = Some(path.try_into().unwrap());
        Uri::from_parts(parts).unwrap()
    }

Because there's two possible error types here (http::uri::InvalidUriParts or http::uri::InvalidUri), I need to have an enum error type for this function that can be either of both variants (or Box it, or wrap it in some common type).

This makes my API a mess because now callers need to handle two distinct error types (or a container of various types) for an operation that, realistically, can only fail in a single way (the path_and_query supplied is invalid).

I tried using the Builder pattern, but the type returned by hyper::Uri::scheme cannot passed to http::uri::Builder::scheme, so I end up with a bunch of failure branches again.

These three approaches could work around the issue:

  • Mutate an Uri and change its path_and_query, or
  • Create a new Uri using the Parts from another while changing only one part.
  • Allow creating a builder pre-populated with Parts from an existing Uri. This would allow re-writing the above example in a way that only one error needs to be handled.

The first one has been mentioned in the past and it seems its undesirable, so I'll just ignore it. The second is tricky to design with a clean API. The third is probably the simplest, since the builder can be initialized with the parts from the source Uri.

I think something like this is quite viable:

impl Builder {
    // ...
    pub fn from_uri(uri: Uri) -> Self {
        Builder {
            parts: Ok(uri.into_parts()),
        }
    }

This could then be used as:

        Builder::from_uri(my_uri)
            .path_and_query(path)
            .build()
            .unwrap();

Note that there's only one failure branch (and one error type) that needs to be handled.

Though, perhaps the following is as simple, useful and a bit more correct:

impl Builder {
    // ...
    pub fn from_parts(parts: Parts) -> Self {
        Builder {
            parts: Ok(parts),
        }
    }
Linguagem predominante
Rust
Estrelas
1.4k
Forks
385
Merge médio
1d 5h
PRs com merge (30d)
2

Preparar o ambiente

Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de hyperium/http

Todas as issues de hyperium/http

Issues semelhantes

Mais issues de Rust

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.