libreactor.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <err.h>
  6. #include <sys/eventfd.h>
  7. #include <dynamic.h>
  8. #include <reactor.h>
  9. #include <clo.h>
  10. #include "helpers.h"
  11. static core_status server_handler(core_event *event)
  12. {
  13. static char hello_string[] = "Hello, World!";
  14. static char default_string[] = "Hello from libreactor!\n";
  15. static clo_pair json_pair[] = {{ .string = "message", .value = { .type = CLO_STRING, .string = "Hello, World!" }}};
  16. static clo json_object[] = {{ .type = CLO_OBJECT, .object = json_pair }};
  17. server *server = event->state;
  18. server_context *context = (server_context *) event->data;
  19. if (event->type == SERVER_REQUEST){
  20. if (segment_equal(context->request.target, segment_string("/json"))){
  21. json(context, json_object);
  22. }
  23. else if (segment_equal(context->request.target, segment_string("/plaintext"))){
  24. plaintext(context, hello_string);
  25. }
  26. else{
  27. plaintext(context, default_string);
  28. }
  29. return CORE_OK;
  30. }
  31. else {
  32. warn("error");
  33. server_destruct(server);
  34. return CORE_ABORT;
  35. }
  36. }
  37. int main()
  38. {
  39. int parent_eventfd;
  40. server s;
  41. // fork_workers() forks a separate child/worker process for each available cpu and returns an eventfd from the parent
  42. // The eventfd is used to signal the parent. This guarantees the forking order needed for REUSEPORT_CBPF to work well
  43. parent_eventfd = fork_workers();
  44. core_construct(NULL);
  45. server_construct(&s, server_handler, &s);
  46. server_open(&s, 0, 8080);
  47. enable_reuseport_cbpf(&s);
  48. // Signal the parent process so that it can proceed with the next fork
  49. eventfd_write(parent_eventfd, (eventfd_t) 1);
  50. close(parent_eventfd);
  51. core_loop(NULL);
  52. core_destruct(NULL);
  53. }