中间件底层,websocket

HttpServer.h 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #pragma once
  2. #include "mongoose.h"
  3. #include "RcfEcho.h"
  4. static const char *s_http_addr = "http://0.0.0.0:8000"; // HTTP port
  5. static const char *s_https_addr = "https://0.0.0.0:8443"; // HTTPS port
  6. static const char *s_root_dir = ".";
  7. // We use the same event handler function for HTTP and HTTPS connections
  8. // fn_data is NULL for plain HTTP, and non-NULL for HTTPS
  9. static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
  10. if (ev == MG_EV_ACCEPT && fn_data != NULL) {
  11. //struct mg_tls_opts opts = {
  12. // //.ca = "ca.pem", // Uncomment to enable two-way SSL
  13. // .cert="server.pem", // Certificate PEM file
  14. // .certkey ="server.pem", // This pem contains both cert and key
  15. //};
  16. struct mg_tls_opts opts;
  17. opts.cert = "server.pem";
  18. opts.certkey = "server.pem";
  19. mg_tls_init(c, &opts);
  20. }
  21. else if (ev == MG_EV_HTTP_MSG) {
  22. struct mg_http_message *hm = (struct mg_http_message *) ev_data;
  23. if (mg_http_match_uri(hm, "/api/f1")) {
  24. mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123); // Serve REST
  25. }
  26. else if (mg_http_match_uri(hm, "/api/f2/*")) {
  27. mg_http_reply(c, 200, "", "{\"result\": \"%.*s\"}\n", (int)hm->uri.len,
  28. hm->uri.ptr);
  29. }
  30. else {
  31. /*struct mg_http_serve_opts opts = { .root_dir = s_root_dir };*/
  32. struct mg_http_serve_opts opts ;
  33. opts.root_dir = s_root_dir;
  34. mg_http_serve_dir(c, hm, &opts);
  35. }
  36. }
  37. (void)fn_data;
  38. }
  39. //int main11(void) {
  40. // struct mg_mgr mgr; // Event manager
  41. // mg_log_set("2"); // Set to 3 to enable debug
  42. // mg_mgr_init(&mgr); // Initialise event manager
  43. // mg_http_listen(&mgr, s_http_addr, fn, NULL); // Create HTTP listener
  44. // mg_http_listen(&mgr, s_https_addr, fn, (void *)1); // HTTPS listener
  45. // for (;;) mg_mgr_poll(&mgr, 1000); // Infinite event loop
  46. // mg_mgr_free(&mgr);
  47. // return 0;
  48. //}
  49. class HttpServer
  50. {
  51. public:
  52. void run();
  53. void run(int httpPort,int httpsPort);
  54. private:
  55. static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data);
  56. };