libmoost
/home/mhx/git/github/libmoost/include/moost/murcl/easy.hpp
Go to the documentation of this file.
00001 /* vim:set ts=3 sw=3 sts=3 et: */
00036 #ifndef FM_LAST_MOOST_MURCL_EASY_HPP__
00037 #define FM_LAST_MOOST_MURCL_EASY_HPP__
00038 
00039 #include <stdexcept>
00040 #include <sstream>
00041 
00042 #include <boost/bind.hpp>
00043 
00044 #include <curl/curl.h>
00045 
00046 #include "global.hpp"
00047 #include "option.hpp"
00048 
00049 namespace moost { namespace murcl {
00050 
00054 class easy
00055 {
00056 public:
00057 
00063    typedef boost::shared_ptr<easy> ptr;
00064 
00068    easy() : handle_(0)
00069    {
00070       // if the global env is not configured all bets are off
00071       if(!global_singleton::instance().isok())
00072       {
00073          throw std::runtime_error("Failed to initialise the LibCurl library");
00074       }
00075 
00076       // attempt to create an interface handle
00077       handle_ = curl_easy_init();
00078       if(0 == handle_)
00079       {
00080          throw std::runtime_error("Failed to initialise the LibCurl 'easy' API");
00081       }
00082    }
00083 
00092    template <typename OptionTraits>
00093    void set_option(typename OptionTraits::value_type const & val)
00094    {
00095       optstash_.push_back(
00096          boost::shared_ptr<option<OptionTraits> > (
00097             new option<OptionTraits>(handle_, val)
00098             )
00099          );
00100    }
00101 
00105    ~easy()
00106    {
00107       curl_easy_cleanup(handle_);
00108    }
00109 
00113    void perform() const
00114    {
00115       CURLcode code = curl_easy_perform(handle_);
00116       validate_result(code, "Unable to perform request");
00117    }
00118 
00119 private:
00120 
00121    // general function to simplify error checking
00122    void validate_result(CURLcode const code, std::string const & msg) const
00123    {
00124       if(CURLE_OK == code) { return; }
00125 
00126       std::ostringstream oss;
00127       oss
00128          << msg
00129          << ": "
00130          << curl_easy_strerror(code);
00131 
00132       throw std::runtime_error(oss.str());
00133    }
00134 
00135    CURL * handle_;
00136    option_stash optstash_;
00137 };
00138 
00139 ;
00140 
00141 }}
00142 
00143 #endif //FM_LAST_MOOST_MURCL_EASY_HPP__