Skip to content

Commit

Permalink
Add a way to set a default scheme
Browse files Browse the repository at this point in the history
One very common need is to parse a user-provided struct into an URL.
It is currently quite tedious to do, as one of the requirement is to have a schema.
This make it slightly easier for the common and simple cases.
  • Loading branch information
Geod24 committed May 29, 2019
1 parent 378021c commit 2ee588e
Showing 1 changed file with 28 additions and 9 deletions.
37 changes: 28 additions & 9 deletions inet/vibe/inet/url.d
Original file line number Diff line number Diff line change
Expand Up @@ -109,25 +109,38 @@ struct URL {

/** Constructs a URL from its string representation.
Params:
url_string = the URL to parse
def_schema = the schema to use in the absence of one.
E.g. when parsing user input from a web browser,
one might want to assume `http`, and `file` for other purposes.
If `null` (the default), no schema will throw.
TODO: additional validation required (e.g. valid host and user names and port)
*/
this(string url_string)
this(string url_string, string def_schema = null)
{
auto str = url_string;
enforce(str.length > 0, "Empty URL.");
if( str[0] != '/' ){
auto idx = str.indexOf(':');
enforce(idx > 0, "No schema in URL:"~str);
m_schema = str[0 .. idx];
str = str[idx+1 .. $];
bool requires_host = false;

if (isDoubleSlashSchema(m_schema)) {
// proto://server/path style
enforce(str.startsWith("//"), "URL must start with proto://...");
requires_host = true;
str = str[2 .. $];
if (idx > 0)
{
m_schema = str[0 .. idx];
str = str[idx+1 .. $];
if (isDoubleSlashSchema(m_schema)) {
// proto://server/path style
enforce(str.startsWith("//"), "URL must start with proto://...");
requires_host = true;
str = str[2 .. $];
}
}
else if (def_schema.length)
m_schema = def_schema;
else
throw new Exception("No schema in URL: " ~ str);

auto si = str.indexOf('/');
if( si < 0 ) si = str.length;
Expand Down Expand Up @@ -499,6 +512,12 @@ unittest {
assert(url.localURI == "/echo");
}

// Test for default scheme
unittest {
auto url = URL("vibe-d.org", "http");
assert(url.toString() == "http://vibe-d.org");
}

unittest {
auto p = PosixPath("/foo bar/boo oom/");
URL url = URL("http", "example.com", 0, p); // constructor test
Expand Down

0 comments on commit 2ee588e

Please sign in to comment.