Title here
Summary here
Here’s the translation of the URL parsing example from Go to Nim:
Our URL parsing program demonstrates how to parse URLs in Nim. URLs provide a uniform way to locate resources.
import uri, strutils
proc main() =
# We'll parse this example URL, which includes a
# scheme, authentication info, host, port, path,
# query params, and query fragment.
let s = "postgres://user:pass@host.com:5432/path?k=v#f"
# Parse the URL and ensure there are no errors.
let u = parseUri(s)
# Accessing the scheme is straightforward.
echo u.scheme
# `userinfo` contains all authentication info; we need to split it
# to get individual username and password values.
let userinfo = u.userinfo.split(':')
echo u.userinfo
echo userinfo[0]
echo userinfo[1]
# The `hostname` and `port` are separate in Nim's Uri object.
echo u.hostname & ":" & u.port
echo u.hostname
echo u.port
# Here we extract the `path` and the fragment after the `#`.
echo u.path
echo u.anchor
# To get query params in a string of `k=v` format,
# use `query`. You can also parse query params
# into a Table. The parsed query param table is from
# strings to strings in Nim.
echo u.query
let m = u.query.parseQuery()
echo m
echo m["k"]
main()
Running our URL parsing program shows all the different pieces that we extracted.
$ nim c -r url_parsing.nim
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
{"k": "v"}
v
In this Nim version:
uri
module for URL parsing.parseUri
function is used to parse the URL string.Uri
object in Nim has slightly different field names compared to Go’s URL
struct.userinfo
, which we manually split.Uri
object.anchor
in Nim.Table
using the parseQuery
function.The overall structure and functionality of the program remain the same as the original example, demonstrating URL parsing capabilities in Nim.