Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

URLs

ParseUrl takes a URL apart into a Url, whose fields can be read, changed and printed again. It follows the URL standard, RFC 3986.

#import "std/net"

var u = net.ParseUrl( "http://user@shop.example:8080/cat%C3%A9gorie/../items?id=7&sort=price+asc#reviews" ).Value( )
print "scheme "; u.Scheme; ", user "; u.User; ", host "; u.Host; ", port"; u.Port
print u.Path
print u.RawQuery
print u.Fragment

'' Links on the page, made absolute.
print u.Resolve( "item?id=8" ).Value( ).ToString( )
print u.Resolve( "/" ).Value( ).ToString( )
print u.Resolve( "//cdn.example/app.js" ).Value( ).ToString( )

'' The query, as name/value pairs.
var q = u.Query( )
print q.Get( "sort" ).ValueOr( "" ), q.Get( "missing" ).ValueOr( "(none)" )
q.SetValue( "id", "9" )
q.Add( "tag", "new & used" )
print q.Encode( )

'' Changing a field: ToString escapes it.
u.Path = "/items/summer sale"
u.RawQuery = q.Encode( )
u.Fragment = ""
print u.ToString( )

Output

scheme http, user user, host shop.example, port 8080
/catégorie/../items
id=7&sort=price+asc
reviews
http://user@shop.example:8080/item?id=8
http://user@shop.example:8080/
http://cdn.example/app.js
price asc     (none)
id=9&sort=price+asc&tag=new+%26+used
http://user@shop.example:8080/items/summer%20sale?id=9&sort=price+asc&tag=new+%26+used

The fields hold the parts decoded: Path has é where the URL had %C3%A9. RawQuery is the exception, kept as written, because only a query parser knows where its pairs end; Query( ) is that parser. Port is -1 when the URL names none.

Resolve( link ) turns a link found on a page into an absolute URL, as a browser does: item?id=8 replaces the last segment of the path, / goes to the top of the site, and //cdn.example/app.js keeps only the scheme. Dot segments are removed as the link is resolved — which is why /catégorie/../item became /item.

QueryValues is a list of name and value pairs in order; a name may appear more than once, and GetAll returns every value. Encode( ) writes it back, escaping each name and value, so & inside a value cannot split it.

Setting a field and calling ToString( ) escapes what needs escaping: the space in summer sale becomes %20. A URL with a broken escape, such as a lone %, does not parse at all.

Activities

  1. Print u.Resolve( "../../../x" ).Value( ).ToString( ). Where does it stop?
  2. Parse "http://[::1]:9000/" and print Host and HostPort( ).