Slim3でリクエストから相対パスを取得する

public static String getRelativeUrl(HttpServletRequest request) {

        String baseUrl = null;

        if ((request.getServerPort() == 80) || (request.getServerPort() == 443))
            baseUrl = request.getScheme() + "://" + request.getServerName()
                    + request.getContextPath();
        else
            baseUrl = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + request.getContextPath();

        StringBuffer buf = request.getRequestURL();

        if (request.getQueryString() != null) {
            buf.append("?");
            buf.append(request.getQueryString());
        }

        return buf.substring(baseUrl.length());
    }