Home

Awesome

A Robust URL Parser and Builder for Lua

This small Lua library provides a few functions to parse URL with querystring and build new URL easily.

url = require "net.url"

URL parser

The library converts an URL to a table of the elements as described in RFC : scheme, host, path, etc.

u = url.parse("http://www.example.com/test/?start=10")
print(u.scheme)
-- http
print(u.host)
-- www.example.com
print(u.path)
-- /test/

URL normalization

u = url.parse("http://www.FOO.com:80///foo/../foo/./bar"):normalize()
print(u)
-- http://www.foo.com/foo/bar

URL resolver

URL resolution follows the examples provided in the RFC 2396.

u = url.parse("http://a/b/c/d;p?q"):resolve("../../g")
print(u)
-- http://a/g

Path builder

Path segments can be added using the __div metatable or u.addSegment().

u = url.parse('http://example.com')
u / 'bands' / 'AC/DC'
print(u)
-- http://example.com/bands/AC%2FDC

Module Options

If one wants to have the + sign as is in path segments, one can add it to the list of legal characters in path. For example:

url = require "net.url"
url.options.legal_in_path["+"] = true;

Querystring parser

The library supports brackets in querystrings, like PHP. It means you can use brackets to build multi-dimensional tables. The parsed querystring has a tostring() helper. As usual with Lua, if no index is specified, it starts from index 1.

query = url.parseQuery("first=abc&a[]=123&a[]=false&b[]=str&c[]=3.5&a[]=last")
print(query)
-- a[1]=123&a[2]=false&a[3]=last&b[1]=str&c[1]=3.5&first=abc
print(query.a[1])
-- 123

Querystring builder

u = url.parse("http://www.example.com")
u.query.foo = "bar"
print(u)
-- http://www.example.com/?foo=bar

u:setQuery{ json = true, skip = 100 }
print(u)
-- http://www.example.com/?json=true&skip=100

Differences with luasocket/url.lua