http_server.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #pragma once
  2. #include <stdarg.h>
  3. #include <stdint.h>
  4. #include <string>
  5. #include <system/Thread.h>
  6. namespace srv {
  7. class HttpServer : protected Thread {
  8. public:
  9. typedef void (*UploadFilenameListener)(const std::string& filename);
  10. typedef void (*UploadProgressListener)(uint64_t uploaded_bytes, uint64_t all_bytes);
  11. HttpServer();
  12. virtual ~HttpServer();
  13. virtual bool threadLoop();
  14. /**
  15. * 在新线程运行
  16. */
  17. void RunAsync(int port);
  18. /**
  19. * 在当前线程运行,会阻塞
  20. */
  21. int RunSync(int port);
  22. /**
  23. * 停止
  24. */
  25. void Stop();
  26. /**
  27. * 设置上传文件名回调
  28. */
  29. void set_upload_filename_listener(UploadFilenameListener listener);
  30. /**
  31. * 设置上传进度回调
  32. */
  33. void set_upload_progress_listener(UploadProgressListener listener);
  34. UploadFilenameListener upload_filename_listener();
  35. UploadProgressListener upload_progress_listener();
  36. private:
  37. bool stop_;
  38. int port_;
  39. UploadFilenameListener upload_filename_listener_;
  40. UploadProgressListener upload_progress_listener_;
  41. };
  42. inline std::string format(const char* format, ...) {
  43. std::string tmp;
  44. va_list vl;
  45. va_start(vl, format);
  46. size_t num = vsnprintf(0, 0, format, vl);
  47. if (num >= tmp.capacity()) tmp.reserve(num + sizeof(char));
  48. tmp.resize(num);
  49. vsnprintf((char*)tmp.data(), tmp.capacity(), format, vl);
  50. va_end(vl);
  51. return tmp;
  52. }
  53. } /* namespace srv */