AI 编码
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include <stdio.h>
#include <string.h>
#include <cstdlib>
void post_request_handler(struct evhttp_request *req, void *arg) {
struct evbuffer *input_buf = evhttp_request_get_input_buffer(req);
size_t post_data_len = evbuffer_get_length(input_buf);
printf("POST request with %zu bytes of data\n", post_data_len);
char *post_data = static_cast<char*>(malloc(post_data_len + 1));
char* tmp = nullptr;
if (post_data) {
evbuffer_copyout(input_buf, post_data, post_data_len);
post_data[post_data_len] = '\0';
printf("POST data: %s\n", post_data);
free(post_data);
}
// 创建返回内容
struct evbuffer *output_buf = evbuffer_new();
if (!output_buf) {
puts("Failed to create response buffer");
return;
}
evbuffer_add_printf(output_buf, "POST data received");
evhttp_send_reply(req, HTTP_OK, "OK", output_buf);
evbuffer_free(output_buf);
}
void get_request_handler(struct evhttp_request *req, void *arg) {
const char *uri = evhttp_request_get_uri(req);
struct evhttp_uri *decoded_uri = evhttp_uri_parse(uri);
if (!decoded_uri) {
printf("Bad URI: %s\n", uri);
evhttp_send_error(req, HTTP_BADREQUEST, 0);
return;
}
const char *path = evhttp_uri_get_path(decoded_uri);
const char *query = evhttp_uri_get_query(decoded_uri);
if (query) {
struct evkeyvalq params;
evhttp_parse_query_str(query, ¶ms);
struct evkeyval *param;
for (param = params.tqh_first; param; param = param->next.tqe_next) {
//TODO: params query
}
}
struct evbuffer *buf = evbuffer_new();
if (!buf) {
puts("Failed to create response buffer");
return;
}
evbuffer_add_printf(buf, "Hello! You requested %s", uri);
evhttp_send_reply(req, HTTP_OK, "OK", buf);
evhttp_uri_free(decoded_uri);
evbuffer_free(buf);
}
void req_handler(struct evhttp_request *req,void *arg){
auto command = evhttp_request_get_command(req);
if(command == EVHTTP_REQ_GET){
get_request_handler(req, arg);
}else if(command == EVHTTP_REQ_POST){
post_request_handler(req, arg);
}else{
printf("Not Find Request Command ... ...\n");
}
}
int main() {
struct event_base *base;
struct evhttp *http;
struct evhttp_bound_socket *handle;
base = event_base_new();
if (!base) {
puts("Couldn't create an event_base");
return 1;
}
http = evhttp_new(base);
if (!http) {
puts("Couldn't create evhttp");
return 1;
}
evhttp_set_gencb(http, req_handler, NULL);
handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", 8080);
if (!handle) {
puts("Couldn't bind to port 8080");
return 1;
}
event_base_dispatch(base);
evhttp_free(http);
event_base_free(base);
return 0;
}
使用 wget 简易测试了下,可以用