1 // This may look like C code, but it's really -*- C++ -*- 2 /* 3 * Copyright (C) 2011 Emweb bv, Herent, Belgium. 4 * 5 * See the LICENSE file for terms of use. 6 */ 7 #ifndef WSTREAM_RESOURCE_H_ 8 #define WSTREAM_RESOURCE_H_ 9 10 #include <Wt/WResource.h> 11 12 #include <string> 13 14 namespace Wt { 15 16 /*! \class WStreamResource Wt/WStreamResource.h Wt/WStreamResource.h 17 * \brief An object which streams the data from a std::istream. 18 * 19 * This class can be useful base for implementing resources which streams 20 * the data from std::istream derivatives. 21 * 22 * The utility method handleRequestPiecewise() makes use of continuations 23 * to transmit data piecewise, without blocking a thread or requiring the 24 * whole data to be read in memory. The size of the buffer can be changed 25 * by using setBufferSize(). 26 * 27 * \if cpp 28 * Example for a custom stream resource implementation: 29 * \code 30 class MyStreamResource : public Wt::WStreamResource 31 { 32 public: 33 MyStreamResource(const std::string& fileName) 34 : Wt::WStreamResource(), 35 fileName_(fileName) 36 { 37 suggestFileName("data.txt"); 38 } 39 40 ~MyStreamResource() { 41 beingDeleted(); 42 } 43 44 void handleRequest(const Wt::Http::Request& request, 45 Wt::Http::Response& response) { 46 std::ifstream r(fileName_.c_str(), std::ios::in | std::ios::binary); 47 handleRequestPiecewise(request, response, r); 48 } 49 50 private: 51 std::string fileName_; 52 }; 53 * \endcode 54 * \endif 55 * 56 * \sa WFileResource 57 */ 58 class WT_API WStreamResource : public WResource 59 { 60 public: 61 /*! \brief Default constructor. 62 * 63 * The mime type defaults to "text/plain". 64 */ 65 WStreamResource(); 66 67 /*! \brief Creates a new resource with given mime-type. 68 */ 69 WStreamResource(const std::string& mimeType); 70 71 /*! \brief Destructor. 72 * 73 * It is up to the user to make sure that the resource is no longer 74 * in use (by e.g. a WImage). 75 */ 76 ~WStreamResource(); 77 78 /*! \brief Sets the mime-type. 79 */ 80 void setMimeType(const std::string& mimeType); 81 82 /*! \brief Returns the mime-type. 83 */ mimeType()84 const std::string& mimeType() const { return mimeType_; } 85 86 /*! \brief Configures the buffer size. 87 * 88 * This configures the size of the buffer used to transmit the data 89 * piece by piece. 90 */ 91 void setBufferSize(int size); 92 93 /*! \brief Returns the buffer size. 94 * 95 * \sa setBufferSize() 96 */ bufferSize()97 int bufferSize() const { return bufferSize_; } 98 99 protected: 100 /*! \brief Handles a request and streams the data from a std::istream. 101 * 102 * You can call this method from a custom handleRequest() implementations. 103 */ 104 void handleRequestPiecewise(const Http::Request& request, 105 Http::Response& response, std::istream& input); 106 107 private: 108 std::string mimeType_; 109 int bufferSize_; 110 std::streamsize beyondLastByte_; 111 }; 112 113 } 114 115 #endif // WSTREAM_RESOURCE_H_ 116