Skip to content

Commit

Permalink
Add a way to set a default schema
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 Jun 26, 2019
1 parent 54273f7 commit 7a074d7
Showing 1 changed file with 32 additions and 12 deletions.
44 changes: 32 additions & 12 deletions inet/vibe/inet/url.d
Original file line number Diff line number Diff line change
Expand Up @@ -110,28 +110,42 @@ 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];
enforce(m_schema[0].isAlpha,
"Schema must start with an alphabetical char, found: " ~
m_schema[0]);
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);

enforce(m_schema[0].isAlpha,
"Schema must start with an alphabetical char, found: " ~
m_schema[0]);

auto si = str.indexOf('/');
if( si < 0 ) si = str.length;
Expand Down Expand Up @@ -503,6 +517,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 7a074d7

Please sign in to comment.