FileCache.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #ifndef HV_FILE_CACHE_H_
  2. #define HV_FILE_CACHE_H_
  3. #include <map>
  4. #include <string>
  5. #include "hbuf.h"
  6. #include "hfile.h"
  7. #include "hstring.h"
  8. #include "hmutex.h"
  9. #define HTTP_HEADER_MAX_LENGTH 1024 // 1k
  10. typedef struct file_cache_s {
  11. //std::string filepath;
  12. struct stat st;
  13. time_t open_time;
  14. time_t stat_time;
  15. uint32_t stat_cnt;
  16. HBuf buf; // http_header + file_content
  17. hbuf_t filebuf;
  18. hbuf_t httpbuf;
  19. char last_modified[64];
  20. char etag[64];
  21. const char* content_type;
  22. file_cache_s() {
  23. stat_cnt = 0;
  24. content_type = NULL;
  25. }
  26. void resize_buf(int filesize) {
  27. buf.resize(HTTP_HEADER_MAX_LENGTH + filesize);
  28. filebuf.base = buf.base + HTTP_HEADER_MAX_LENGTH;
  29. filebuf.len = filesize;
  30. }
  31. void prepend_header(const char* header, int len) {
  32. if (len > HTTP_HEADER_MAX_LENGTH) return;
  33. httpbuf.base = filebuf.base - len;
  34. httpbuf.len = len + filebuf.len;
  35. memcpy(httpbuf.base, header, len);
  36. }
  37. } file_cache_t;
  38. // filepath => file_cache_t
  39. typedef std::map<std::string, file_cache_t*> FileCacheMap;
  40. #define DEFAULT_FILE_STAT_INTERVAL 10 // s
  41. #define DEFAULT_FILE_CACHED_TIME 60 // s
  42. class FileCache {
  43. public:
  44. int file_stat_interval;
  45. int file_cached_time;
  46. FileCacheMap cached_files;
  47. std::mutex mutex_;
  48. FileCache() {
  49. file_stat_interval = DEFAULT_FILE_STAT_INTERVAL;
  50. file_cached_time = DEFAULT_FILE_CACHED_TIME;
  51. }
  52. ~FileCache() {
  53. for (auto& pair : cached_files) {
  54. delete pair.second;
  55. }
  56. cached_files.clear();
  57. }
  58. file_cache_t* Open(const char* filepath, void* ctx = NULL);
  59. int Close(const char* filepath);
  60. protected:
  61. file_cache_t* Get(const char* filepath);
  62. };
  63. #endif // HV_FILE_CACHE_H_