responseheaders.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #include <microhttpd.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <time.h>
  6. #define PORT 8888
  7. #define FILENAME "picture.png"
  8. #define MIMETYPE "image/png"
  9. long
  10. get_file_size (const char *filename)
  11. {
  12. FILE *fp;
  13. fp = fopen (filename, "rb");
  14. if (fp)
  15. {
  16. long size;
  17. if ((0 != fseek (fp, 0, SEEK_END)) || (-1 == (size = ftell (fp))))
  18. size = 0;
  19. fclose (fp);
  20. return size;
  21. }
  22. else
  23. return 0;
  24. }
  25. int
  26. answer_to_connection (void *cls, struct MHD_Connection *connection,
  27. const char *url, const char *method,
  28. const char *version, const char *upload_data,
  29. unsigned int *upload_data_size, void **con_cls)
  30. {
  31. unsigned char *buffer = NULL;
  32. struct MHD_Response *response;
  33. long size;
  34. FILE *fp;
  35. int ret = 0;
  36. if (0 != strcmp (method, "GET"))
  37. return MHD_NO;
  38. size = get_file_size (FILENAME);
  39. if (size != 0)
  40. {
  41. fp = fopen (FILENAME, "rb");
  42. if (fp)
  43. {
  44. buffer = malloc (size);
  45. if (buffer)
  46. if (size == fread (buffer, 1, size, fp))
  47. ret = 1;
  48. fclose (fp);
  49. }
  50. }
  51. if (!ret)
  52. {
  53. const char *errorstr =
  54. "<html><body>An internal server error has occured!\
  55. </body></html>";
  56. if (buffer)
  57. free (buffer);
  58. response =
  59. MHD_create_response_from_data (strlen (errorstr), (void *) errorstr,
  60. MHD_NO, MHD_NO);
  61. if (response)
  62. {
  63. ret =
  64. MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
  65. response);
  66. MHD_destroy_response (response);
  67. return MHD_YES;
  68. }
  69. else
  70. return MHD_NO;
  71. }
  72. response =
  73. MHD_create_response_from_data (size, (void *) buffer, MHD_YES, MHD_NO);
  74. MHD_add_response_header (response, "Content-Type", MIMETYPE);
  75. ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
  76. MHD_destroy_response (response);
  77. return ret;
  78. }
  79. int
  80. main ()
  81. {
  82. struct MHD_Daemon *daemon;
  83. daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
  84. &answer_to_connection, NULL, MHD_OPTION_END);
  85. if (NULL == daemon)
  86. return 1;
  87. getchar ();
  88. MHD_stop_daemon (daemon);
  89. return 0;
  90. }