1 /** 2 * ae.net.ietf.url 3 * 4 * License: 5 * This Source Code Form is subject to the terms of 6 * the Mozilla Public License, v. 2.0. If a copy of 7 * the MPL was not distributed with this file, You 8 * can obtain one at http://mozilla.org/MPL/2.0/. 9 * 10 * Authors: 11 * Vladimir Panteleev <vladimir@thecybershadow.net> 12 */ 13 14 module ae.net.ietf.url; 15 16 import std.exception; 17 import std.string; 18 19 import ae.utils.array; 20 21 string applyRelativeURL(string base, string rel) 22 { 23 if (rel.indexOf("://") >= 0) 24 return rel; 25 26 base = base.split("?")[0]; 27 base = base[0..base.lastIndexOf('/')+1]; 28 while (true) 29 { 30 if (rel.startsWith("../")) 31 { 32 rel = rel[3..$]; 33 base = base[0..base[0..$-1].lastIndexOf('/')+1]; 34 enforce(base.length, "Bad relative URL"); 35 } 36 else 37 if (rel.startsWith("/")) 38 return base.split("/").slice(0, 3).join("/") ~ rel; 39 else 40 return base ~ rel; 41 } 42 } 43 44 unittest 45 { 46 assert(applyRelativeURL("http://example.com/", "index.html") == "http://example.com/index.html"); 47 assert(applyRelativeURL("http://example.com/index.html", "page.html") == "http://example.com/page.html"); 48 assert(applyRelativeURL("http://example.com/dir/index.html", "page.html") == "http://example.com/dir/page.html"); 49 assert(applyRelativeURL("http://example.com/dir/index.html", "/page.html") == "http://example.com/page.html"); 50 assert(applyRelativeURL("http://example.com/dir/index.html", "../page.html") == "http://example.com/page.html"); 51 assert(applyRelativeURL("http://example.com/script.php?path=a/b/c", "page.html") == "http://example.com/page.html"); 52 assert(applyRelativeURL("http://example.com/index.html", "http://example.org/page.html") == "http://example.org/page.html"); 53 } 54 55 string fileNameFromURL(string url) 56 { 57 return url.split("?")[0].split("/")[$-1]; 58 } 59 60 unittest 61 { 62 assert(fileNameFromURL("http://example.com/index.html") == "index.html"); 63 assert(fileNameFromURL("http://example.com/dir/index.html") == "index.html"); 64 assert(fileNameFromURL("http://example.com/script.php?path=a/b/c") == "script.php"); 65 }