app.url - URL 解析与构建 API
URL 解析、构建和编码操作。
权限级别: L0(安全,始终可用)
方法
app.url.parse(urlString)
解析 URL 为组件表。
参数:
urlString(string) - URL 字符串
返回值: table, error - URL 组件
local url = app.url.parse("https://user:pass@example.com:8080/path?q=test&lang=zh#section")
-- {
-- scheme = "https",
-- host = "example.com",
-- port = 8080,
-- path = "/path",
-- query = "q=test&lang=zh",
-- fragment = "section",
-- user = "user",
-- password = "pass",
-- queryParams = {q = "test", lang = "zh"}
-- }
app.url.build(components)
从组件表构建 URL。
参数:
components(table) - URL 组件(支持字段同parse()返回值)
返回值: string, error
local url = app.url.build({
scheme = "https",
host = "api.example.com",
path = "/v1/search",
queryParams = {q = "hello", page = "1"}
})
-- "https://api.example.com/v1/search?page=1&q=hello"
app.url.encodeQuery(params)
将参数表编码为查询字符串。
参数:
params(table) - 键值对
返回值: string - 编码后的查询字符串(不含 ?)
local qs = app.url.encodeQuery({name = "张三", age = "30"})
-- "age=30&name=%E5%BC%A0%E4%B8%89"
app.url.decodeQuery(queryString)
解码查询字符串为参数表。
参数:
queryString(string) - 查询字符串(可含前导?)
返回值: table
local params = app.url.decodeQuery("?name=%E5%BC%A0%E4%B8%89&age=30")
-- {name = "张三", age = "30"}
app.url.encode(str)
URL 编码。
参数:
str(string) - 原始字符串
返回值: string
local encoded = app.url.encode("hello world/你好")
app.url.decode(str)
URL 解码。
参数:
str(string) - 编码后的字符串
返回值: string
local decoded = app.url.decode("hello%20world") -- "hello world"
示例
构建 API 请求 URL
function MyPlugin:buildAPIUrl(endpoint, params)
return app.url.build({
scheme = "https",
host = "api.example.com",
path = "/v2/" .. endpoint,
queryParams = params
})
end
local url = self:buildAPIUrl("search", {q = "test", limit = "10"})
local result = app.http.get(url)