public static int serveFile(File base, String context,
            Request req, Response resp) throws IOException {
        String relativePath = req.getPath().substring(context.length());
        File file = new File(base, relativePath).getCanonicalFile();
        if (!file.exists() || file.isHidden()) {
            return 404;
        } else if (!file.canRead()
                   || !file.getPath().startsWith(base.getPath())) { // validate
            return 403;
        } else if (file.isDirectory()) {
            if (relativePath.endsWith("/") || relativePath.length() == 0) {
                if (!req.getVirtualHost().isAllowGeneratedIndex())
                    return 403;
                resp.send(200, createIndex(file, req.getPath()));
            } else { // redirect to the normalized directory URL ending with '/'
                resp.redirect(req.getBaseURL() + req.getPath() + "/", true);
            }
        } else {
            serveFileContent(file, req, resp);
        }
        return 0;
    }