#include "base/Url.h" #include #include base::Url::Url() { SetUrl(std::string()); } base::Url::Url(const char* url) { SetUrl(std::string(url ? url : "")); } base::Url::Url(const std::string& url) { SetUrl(url); } base::Url::~Url() { } bool base::Url::SetUrl(const std::string& url, bool showerr) { fValid = false; fUrl.clear(); fProtocol.clear(); fHostName.clear(); fPort = 0; fFileName.clear(); fOptions.clear(); if (url.length()==0) return false; fUrl = url; fValid = true; std::string s = fUrl; std::size_t pos = s.find("://"); if (pos != std::string::npos) { fProtocol = s.substr(0, pos); s.erase(0, pos + 3); } if (s.length() == 0) return fValid; pos = s.rfind("?"); if (pos != std::string::npos) { fOptions = s.substr(pos+1); s.erase(pos); } pos = s.find("/"); if (pos==0) { fFileName = s; } else if (pos != std::string::npos) { fHostName = s.substr(0, pos); fFileName = s.substr(pos+1); } else { fHostName = s; } pos = fHostName.find(":"); if (pos != std::string::npos) { char* errpos = 0; fPort = strtol(fHostName.c_str()+pos+1, &errpos, 10); if (errpos!=0) { if (showerr) fprintf(stderr, "Invalid URL format:%s - wrong port number\n", fHostName.c_str()); fValid = false; } else { fHostName.erase(pos); } } return fValid; } std::string base::Url::GetFullName() const { if (fFileName.length()==0) return fHostName; if (fHostName.length()==0) return fFileName; std::string res = fHostName; res+="/"; res+=fFileName; return res; } std::string base::Url::GetPortStr() const { if (fPort<=0) return std::string(); char sbuf[80]; sprintf(sbuf, "%d", fPort); return std::string(sbuf); } bool base::Url::GetOption(const std::string& optname, std::string* value) const { if (value) value->clear(); if (optname.empty() || fOptions.empty()) return false; int p = 0; while (p < fOptions.length()) { int separ = fOptions.find("&", p); if (separ==std::string::npos) separ = fOptions.length(); // printf("Search for option %s fullstr %s p=%d separ=%d\n", optname.c_str(), fOptions.c_str(), p, separ); if (separ-p >= optname.length()) { bool find = fOptions.compare(p, optname.length(), optname)==0; if (find) { p+=optname.length(); // this is just option name, nothing else - value is empty http://host?option if (p==separ) return true; if (fOptions[p]=='=') { // also empty option possible, but with syntax http://host?option= p++; if ((p