responseheaders.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* Feel free to use this example code in any way
  2. you see fit (Public Domain) */
  3. #include <sys/types.h>
  4. #ifndef _WIN32
  5. #include <sys/select.h>
  6. #include <sys/socket.h>
  7. #else
  8. #include <winsock2.h>
  9. #endif
  10. #include <microhttpd.h>
  11. #include <time.h>
  12. #include <sys/stat.h>
  13. #include <fcntl.h>
  14. #include <string.h>
  15. #include <stdio.h>
  16. #define PORT 8888
  17. #define FILENAME "picture.png"
  18. #define MIMETYPE "image/png"
  19. static int
  20. answer_to_connection (void *cls, struct MHD_Connection *connection,
  21. const char *url, const char *method,
  22. const char *version, const char *upload_data,
  23. size_t *upload_data_size, void **con_cls)
  24. {
  25. struct MHD_Response *response;
  26. int fd;
  27. int ret;
  28. struct stat sbuf;
  29. (void)cls; /* Unused. Silent compiler warning. */
  30. (void)url; /* Unused. Silent compiler warning. */
  31. (void)version; /* Unused. Silent compiler warning. */
  32. (void)upload_data; /* Unused. Silent compiler warning. */
  33. (void)upload_data_size; /* Unused. Silent compiler warning. */
  34. (void)con_cls; /* Unused. Silent compiler warning. */
  35. if (0 != strcmp (method, "GET"))
  36. return MHD_NO;
  37. if ( (-1 == (fd = open (FILENAME, O_RDONLY))) ||
  38. (0 != fstat (fd, &sbuf)) )
  39. {
  40. const char *errorstr =
  41. "<html><body>An internal server error has occured!\
  42. </body></html>";
  43. /* error accessing file */
  44. if (fd != -1)
  45. (void) close (fd);
  46. response =
  47. MHD_create_response_from_buffer (strlen (errorstr),
  48. (void *) errorstr,
  49. MHD_RESPMEM_PERSISTENT);
  50. if (NULL != response)
  51. {
  52. ret =
  53. MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
  54. response);
  55. MHD_destroy_response (response);
  56. return ret;
  57. }
  58. else
  59. return MHD_NO;
  60. }
  61. response =
  62. MHD_create_response_from_fd_at_offset64 (sbuf.st_size, fd, 0);
  63. MHD_add_response_header (response, "Content-Type", MIMETYPE);
  64. ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
  65. MHD_destroy_response (response);
  66. return ret;
  67. }
  68. int
  69. main ()
  70. {
  71. struct MHD_Daemon *daemon;
  72. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
  73. &answer_to_connection, NULL, MHD_OPTION_END);
  74. if (NULL == daemon)
  75. return 1;
  76. (void) getchar ();
  77. MHD_stop_daemon (daemon);
  78. return 0;
  79. }