use a file source object to abstract loading of resources
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
#include <mbgl/util/filesource.hpp>
|
||||
#include <mbgl/platform/platform.hpp>
|
||||
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
FileSource::FileSource(const std::shared_ptr<uv::loop> &loop)
|
||||
@@ -18,10 +21,39 @@ const std::string &FileSource::getBase() const {
|
||||
void FileSource::load(ResourceType type, const std::string &url, std::function<void(platform::Response *)> callback) {
|
||||
// convert relative URLs to absolute URLs
|
||||
|
||||
// try to load from disk (not yet)
|
||||
const std::string absoluteURL = [&]() -> std::string {
|
||||
const size_t separator = url.find("://");
|
||||
if (separator == std::string::npos) {
|
||||
// Relative URL.
|
||||
return base + url;
|
||||
} else {
|
||||
return url;
|
||||
}
|
||||
}();
|
||||
|
||||
// load from the internet
|
||||
platform::request_http(url, callback, loop);
|
||||
const size_t separator = absoluteURL.find("://");
|
||||
const std::string protocol = separator != std::string::npos ? absoluteURL.substr(0, separator) : "";
|
||||
|
||||
if (protocol == "file") {
|
||||
// load from disk
|
||||
const std::string path = absoluteURL.substr(separator + 3);
|
||||
std::ifstream file(path);
|
||||
|
||||
platform::Response response(callback);
|
||||
if (!file.good()) {
|
||||
response.error_message = "file not found (" + path + ")";
|
||||
} else {
|
||||
std::stringstream data;
|
||||
data << file.rdbuf();
|
||||
response.code = 200;
|
||||
response.body = data.str();
|
||||
}
|
||||
|
||||
callback(&response);
|
||||
} else {
|
||||
// load from the internet
|
||||
platform::request_http(absoluteURL, callback, loop);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user