1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
#
#
# Nimrod's Runtime Library
# (c) Copyright 2010 Dominik Picheta
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## Parses & constructs URLs.
import strutils
type
TURL* = tuple[ ## represents a *Uniform Resource Locator* (URL)
## any optional component is "" if it does not exist
scheme, username, password,
hostname, port, path, query, anchor: string]
proc parseUrl*(url: string): TURL =
var i: int = 0
var scheme, username, password: string = ""
var hostname, port, path, query, anchor: string = ""
var temp: string = ""
if url[i] != '/': #url isn't a relative path
while True:
#Scheme
if url[i] == ':':
if url[i+1] == '/' and url[i+2] == '/':
scheme = temp
temp = ""
inc(i, 3) #Skip the //
#Authority(username, password)
if url[i] == '@':
username = temp.split(':')[0]
if temp.split(':').len() > 1:
password = temp.split(':')[1]
temp = ""
inc(i) #Skip the @
#hostname(subdomain, domain, port)
if url[i] == '/' or url[i] == '\0':
hostname = temp
if hostname.split(':').len() > 1:
port = hostname.split(':')[1]
hostname = hostname.split(':')[0]
temp = ""
break
temp.add(url[i])
inc(i)
if url[i] == '/': inc(i) # Skip the '/'
#Path
while True:
if url[i] == '?':
path = temp
temp = ""
if url[i] == '#':
if temp[0] == '?':
query = temp
else:
path = temp
temp = ""
if url[i] == '\0':
if temp[0] == '?':
query = temp
elif temp[0] == '#':
anchor = temp
else:
path = temp
break
temp.add(url[i])
inc(i)
return (scheme, username, password, hostname, port, path, query, anchor)
proc `$`*(t: TURL): string =
result = ""
if t.scheme != "": result.add(t.scheme & "://")
if t.username != "":
if t.password != "":
result.add(t.username & ":" & t.password & "@")
else:
result.add(t.username & "@")
result.add(t.hostname)
if t.port != "": result.add(":" & t.port)
if t.path != "": result.add("/" & t.path)
result.add(t.query)
result.add(t.anchor)
|