FileCache.h 1.8 KB

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