From 7a074d7ff4ace344e6544dd0cfaf5313a681ccb9 Mon Sep 17 00:00:00 2001 From: Geod24 Date: Tue, 28 May 2019 01:20:03 +0900 Subject: [PATCH] Add a way to set a default schema 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. --- inet/vibe/inet/url.d | 44 ++++++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/inet/vibe/inet/url.d b/inet/vibe/inet/url.d index e6a4178c46..e73db7f89d 100644 --- a/inet/vibe/inet/url.d +++ b/inet/vibe/inet/url.d @@ -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; @@ -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