responseheaders.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <sys/types.h>
  2. #include <sys/select.h>
  3. #include <sys/socket.h>
  4. #include <microhttpd.h>
  5. #include <time.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. #include <string.h>
  9. #define PORT 8888
  10. #define FILENAME "picture.png"
  11. #define MIMETYPE "image/png"
  12. static int
  13. answer_to_connection (void *cls, struct MHD_Connection *connection,
  14. const char *url, const char *method,
  15. const char *version, const char *upload_data,
  16. size_t *upload_data_size, void **con_cls)
  17. {
  18. struct MHD_Response *response;
  19. int fd;
  20. int ret;
  21. struct stat sbuf;
  22. if (0 != strcmp (method, "GET"))
  23. return MHD_NO;
  24. if ( (-1 == (fd = open (FILENAME, O_RDONLY))) ||
  25. (0 != fstat (fd, &sbuf)) )
  26. {
  27. /* error accessing file */
  28. if (fd != -1) close (fd);
  29. const char *errorstr =
  30. "<html><body>An internal server error has occured!\
  31. </body></html>";
  32. response =
  33. MHD_create_response_from_buffer (strlen (errorstr),
  34. (void *) errorstr,
  35. MHD_RESPMEM_PERSISTENT);
  36. if (response)
  37. {
  38. ret =
  39. MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
  40. response);
  41. MHD_destroy_response (response);
  42. return MHD_YES;
  43. }
  44. else
  45. return MHD_NO;
  46. }
  47. response =
  48. MHD_create_response_from_fd_at_offset (sbuf.st_size, fd, 0);
  49. MHD_add_response_header (response, "Content-Type", MIMETYPE);
  50. ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
  51. MHD_destroy_response (response);
  52. return ret;
  53. }
  54. int
  55. main ()
  56. {
  57. struct MHD_Daemon *daemon;
  58. daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
  59. &answer_to_connection, NULL, MHD_OPTION_END);
  60. if (NULL == daemon)
  61. return 1;
  62. getchar ();
  63. MHD_stop_daemon (daemon);
  64. return 0;
  65. }