main.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (c) 2022 Cesanta Software Limited
  2. // All rights reserved
  3. //
  4. // This example demonstrates how to push data over a REST API
  5. // We're going to send a JSON array of some integer values, s_data.
  6. // Periodically, s_data changes, which is tracked by s_version.
  7. // Clients inform their current version, we only send on version mismatch,
  8. // or when version is zero (client has no data); this minimizes traffic and
  9. // avoids updating the UI unnecesarily.
  10. //
  11. // 1. Start this server, type `make`
  12. // 2. Open http://localhost:8000 in your browser
  13. #include "mongoose.h"
  14. static const char *s_listen_on = "http://localhost:8000";
  15. static const char *s_root_dir = "web_root";
  16. #define DATA_SIZE 10 // Total number of elements
  17. static int s_data[DATA_SIZE]; // Simulate some complex data
  18. static long s_version = 0; // Data "version"
  19. static long getparam(struct mg_http_message *hm, const char *json_path) {
  20. double dv = 0;
  21. mg_json_get_num(hm->body, json_path, &dv);
  22. return dv;
  23. }
  24. static size_t printdata(mg_pfn_t out, void *ptr, va_list *ap) {
  25. const char *comma = "";
  26. size_t n = 0;
  27. for (int i = 0; i < DATA_SIZE; ++i) {
  28. n += mg_xprintf(out, ptr, "%s%d", comma, s_data[i]);
  29. comma = ",";
  30. }
  31. return n;
  32. (void) ap;
  33. }
  34. static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
  35. if (ev == MG_EV_HTTP_MSG) {
  36. struct mg_http_message *hm = ev_data;
  37. if (mg_http_match_uri(hm, "/api/data")) {
  38. long version = getparam(hm, "$.version");
  39. if (version > 0 && version == s_version) {
  40. // Version match: no changes
  41. mg_http_reply(c, 200, "Content-Type: application/json\r\n",
  42. "{%Q:%Q,%Q:%ld}\n", "status", "no change", "version",
  43. version);
  44. } else {
  45. // Version mismatch, return data
  46. mg_http_reply(c, 200, "Content-Type: application/json\r\n",
  47. "{%Q:%ld,%Q:[%M]}\n", "version", s_version, "data",
  48. printdata);
  49. }
  50. } else {
  51. struct mg_http_serve_opts opts = {.root_dir = s_root_dir};
  52. mg_http_serve_dir(c, hm, &opts);
  53. }
  54. }
  55. (void) fn_data;
  56. }
  57. static void timer_fn(void *arg) {
  58. for (int i = 0; i < DATA_SIZE; i++) {
  59. s_data[i] = rand();
  60. }
  61. s_version++;
  62. (void) arg;
  63. }
  64. int main(void) {
  65. struct mg_mgr mgr;
  66. mg_mgr_init(&mgr);
  67. srand(time(NULL));
  68. mg_timer_add(&mgr, 5000, MG_TIMER_REPEAT | MG_TIMER_RUN_NOW, timer_fn, NULL);
  69. mg_http_listen(&mgr, s_listen_on, fn, NULL);
  70. for (;;) mg_mgr_poll(&mgr, 1000);
  71. mg_mgr_free(&mgr);
  72. return 0;
  73. }