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