成语在Elixir中使用查询字符串构造URI [英] Idiom to construct a URI with a query string in Elixir

查看:59
本文介绍了成语在Elixir中使用查询字符串构造URI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道最常见的方式是使用 URI 将查询字符串添加到Elixir中的基本URI.

I'm wondering what the most idiomatic way is to use URI to add a query string to a base URI in Elixir.

我目前正在做这样的事情:

I'm currently doing something like this:

iex(1)> base = "http://example.com/endpoint"
"http://example.com/endpoint"

iex(2)> query_string = URI.encode_query(foo: "bar")
"foo=bar"

iex(3)> uri_string = URI.parse(base) |> Map.put(:query, query_string) |> URI.to_string
"http://example.com/endpoint?foo=bar"

但是我想知道是否有一种更干净的方法来设置查询字符串.我知道 URI.merge/2 ,但是我认为查询字符串不是有效的URI,因此此处可能不合适(不会添加?).

But was wondering if there is a cleaner way to set the query string. I know about URI.merge/2, but I don't think a query string is a valid URI, so that's probably not approriate here (the ? will not be added).

我还可以做类似的事情:

I could also do something like:

uri_string = %URI{ URI.parse(base) | query: query_string } |> URI.to_string

但是我想知道是否有一种更简单或更清晰的方法我错过了.

But I'm wondering if there is a simpler or clearer method I've missed.

推荐答案

我认为您的第一个示例(带有某些格式)读起来很不错:

I think your first example, with some formatting, reads pretty well:

uri_string =
  base_url
  |> URI.parse()
  |> Map.put(:query, URI.encode_query(params))
  |> URI.to_string()

我不知道其他惯用语/快捷方式.

I'm not aware of other idioms/shortcuts.

这篇关于成语在Elixir中使用查询字符串构造URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆