gpt4 book ai didi

c++ - 在 C 中使用 SSL 的 mongoose 网络服务器的 hello world 示例

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:47 24 4
gpt4 key购买 nike

我正在尝试使用自签名 SSL 证书设置 mongoose 网络服务器 v3.3。我知道如何在没有 SSL 的情况下执行此操作,但我想实现 HTTPS。

我已经实现了这样的东西:

void *event_handler(enum mg_event event,
struct mg_connection *conn) {

const struct mg_request_info *request_info = mg_get_request_info(conn);

static void* done = "done";

if (event == MG_NEW_REQUEST) {
if (strcmp(request_info->uri, "/hello") == 0) {
// handle c[renderer] request
if(strcmp(request_info->request_method, "GET") != 0) {
// send error (we only care about HTTP GET)
mg_printf(conn, "HTTP/1.1 %d Error (%s)\r\n\r\n%s",
500,
"we only care about HTTP GET",
"we only care about HTTP GET");
// return not null means we handled the request
return done;
}

// handle your GET request to /hello
char* content = "Hello World!";
char* mimeType = "text/plain";
int contentLength = strlen(content);

mg_printf(conn,
"HTTP/1.1 200 OK\r\n"
"Cache: no-cache\r\n"
"Content-Type: %s\r\n"
"Content-Length: %d\r\n"
"\r\n",
mimeType,
contentLength);
mg_write(conn, content, contentLength);
return done;
}
}
// in this example i only handle /hello
mg_printf(conn, "HTTP/1.1 %d Error (%s)\r\n\r\n%s",
500, /* This the error code you want to send back*/
"Invalid Request.",
"Invalid Request.");
return done;
}

// No suitable handler found, mark as not processed. Mongoose will
// try to serve the request.
return NULL;
}

int main(int argc, char **argv) {

const char *options[] = {
"ssl_certificate", "cert.pem",
"listening_ports", "443s",
"num_threads", "10",
NULL
};

static struct mg_context *ctx;

ctx = mg_start(&event_handler, options);
if(ctx == NULL) {
exit(EXIT_FAILURE);
}

puts("Server running, press enter to exit\n");
getchar();
mg_stop(ctx);

return EXIT_SUCCESS;
}

问题是我无法从网络浏览器访问我的服务器。我认为问题是我的回调收到的第一个事件是 MG_INIT_SSL 但我不知道如何处理或处理它。有人可以帮忙吗?

最佳答案

首先,我认为您不必在事件处理程序中处理除 MG_NEW_REQUEST 之外的其他事件。

我还会使用 openssl 进行调试:

openssl s_client -connect <hostname:port>

查看 SSL 连接是否已正确设置。

无论如何,Cesanta 确实提供了一个完整的工作示例供您使用:

https://github.com/cesanta/mongoose/tree/master/examples/simplest_web_server_ssl

关于c++ - 在 C 中使用 SSL 的 mongoose 网络服务器的 hello world 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55505946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com