responseheaders.c 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 enum MHD_Result
  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 **req_cls)
  24. {
  25. struct MHD_Response *response;
  26. int fd;
  27. enum MHD_Result 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) req_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 occurred!\
  42. </body></html>";
  43. /* error accessing file */
  44. if (fd != -1)
  45. (void) close (fd);
  46. response =
  47. MHD_create_response_from_buffer_static (strlen (errorstr), errorstr);
  48. if (NULL != response)
  49. {
  50. ret =
  51. MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
  52. response);
  53. MHD_destroy_response (response);
  54. return ret;
  55. }
  56. else
  57. return MHD_NO;
  58. }
  59. response =
  60. MHD_create_response_from_fd_at_offset64 ((size_t) sbuf.st_size,
  61. fd,
  62. 0);
  63. if (MHD_YES !=
  64. MHD_add_response_header (response,
  65. MHD_HTTP_HEADER_CONTENT_TYPE,
  66. MIMETYPE))
  67. {
  68. fprintf (stderr,
  69. "Failed to set content type header!\n");
  70. /* return response without content encoding anyway ... */
  71. }
  72. ret = MHD_queue_response (connection,
  73. MHD_HTTP_OK,
  74. response);
  75. MHD_destroy_response (response);
  76. return ret;
  77. }
  78. int
  79. main (void)
  80. {
  81. struct MHD_Daemon *daemon;
  82. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
  83. &answer_to_connection, NULL, MHD_OPTION_END);
  84. if (NULL == daemon)
  85. return 1;
  86. (void) getchar ();
  87. MHD_stop_daemon (daemon);
  88. return 0;
  89. }