Created
October 13, 2025 11:27
-
-
Save mistivia/9fb59e976a1deaa4373129645ad4a109 to your computer and use it in GitHub Desktop.
libevent http server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <event2/event.h> | |
| #include <event2/http.h> | |
| #include <event2/buffer.h> | |
| #include <event2/util.h> | |
| #define SERVER_PORT 8080 | |
| void generic_request_handler(struct evhttp_request *req, void *arg) { | |
| struct evbuffer *evb = evbuffer_new(); | |
| if (!evb) { | |
| fprintf(stderr, "Failed to create evbuffer!\n"); | |
| evhttp_send_error(req, HTTP_INTERNAL, "Server Error"); | |
| return; | |
| } | |
| const char *response_body = "<h1>Hello, libevent HTTP Server!</h1>\n" | |
| "<p>You requested the path: "; | |
| evbuffer_add_printf(evb, "%s", response_body); | |
| const char *uri = evhttp_request_get_uri(req); | |
| evbuffer_add_printf(evb, "%s</p>", uri ? uri : "/"); | |
| evhttp_add_header(evhttp_request_get_output_headers(req), | |
| "Content-Type", "text/html"); | |
| evhttp_send_reply(req, HTTP_OK, "OK", evb); | |
| evbuffer_free(evb); | |
| printf("Request handled for URI: %s\n", uri ? uri : "/"); | |
| } | |
| int main(int argc, char **argv) { | |
| struct event_base *base = NULL; | |
| struct evhttp *http = NULL; | |
| struct evhttp_bound_socket *handle = NULL; | |
| base = event_base_new(); | |
| if (!base) { | |
| fprintf(stderr, "Could not initialize libevent base!\n"); | |
| return 1; | |
| } | |
| http = evhttp_new(base); | |
| if (!http) { | |
| fprintf(stderr, "Could not create evhttp object!\n"); | |
| event_base_free(base); | |
| return 1; | |
| } | |
| evhttp_set_gencb(http, generic_request_handler, NULL); | |
| handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", SERVER_PORT); | |
| if (!handle) { | |
| fprintf(stderr, "Could not bind to port %d. Maybe it's already in use?\n", SERVER_PORT); | |
| evhttp_free(http); | |
| event_base_free(base); | |
| return 1; | |
| } | |
| printf("Starting libevent HTTP server on http://127.0.0.1:%d\n", SERVER_PORT); | |
| printf("Press Ctrl+C to stop.\n"); | |
| event_base_dispatch(base); | |
| evhttp_free(http); | |
| event_base_free(base); | |
| printf("Server stopped.\n"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment