Search code examples
urlinno-setuppascalscript

Parse hostname and protocol from URL in Inno Setup Pascal Script


Is there any way to get the hostname and protocol from an URL?

My use case:

  1. On installation user inputs the application and API URL
  2. Get hostname allowedOrigins configuration

Example url:

https://somelink.com/#/login
https://someapilink.com/api/

Desired result:

https://somelink.com
https://someapilink.com

Solution

  • Had you really needed full URL parsing, you might make use of ParseURL WinAPI function.

    But if you only need the hostname and protocol, I'd resort to parsing the URL on your own:

    function GetUrlHostName(Url: string): string;
    var
      P: Integer;
    begin
      Result := '';
      P := Pos('://', Url);
      if P > 0 then
      begin
        Result := Copy(Url, P + 3, Length(Url) - P - 1);
        P := Pos('/', Result);
        if P > 0 then Result := Copy(Result, 1, P - 1);
        P := Pos('#', Result);
        if P > 0 then Result := Copy(Result, 1, P - 1);
        P := Pos(':', Result);
        if P > 0 then Result := Copy(Result, 1, P - 1);
      end;
    end;
    
    function GetUrlProtocol(Url: string): string;
    var
      P: Integer;
    begin
      Result := '';
      P := Pos('://', Url);
      if P > 0 then
      begin
        Result := Copy(Url, 1, P - 1);
      end;
    end;
    

    (The GetUrlHostName does not take possible username and password into account)