Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

URL: Add a way to set a default schema #2311

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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