使用 mongoose 搭建HTTP服务端代码示例

从参数query中获取值

mg_http_get_var
示例:
char ss[100];
int len = mg_http_get_var(&hm->query, "ss", ss, 100);

从报头headers中获取值
mg_http_get_header
示例:
auto mgToken = mg_http_get_header(hm, "Token");

POST请求 参数保存在body里面 减少编码的问题
auto doc = yyjson_read(hm->body.ptr, hm->body.len, 0);

HTTP回包示例:

1 auto start = chrono::steady_clock::now();
2 auto dif = chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now() - start).count();
3 char headers[120];
4 sprintf_s(headers, 120, "Cost: %I64u us\r\n", dif);
5 mg_http_reply(c, 200, headers, "");

回传文件

1 struct mg_http_serve_opts opts = { 0 };
2 opts.mime_types = "text/plain; charset=utf-8";
3 mg_http_serve_file(c, hm, "ReadMe.txt", &opts);

HTTP服务端代码示例:

 1 static void fn(struct mg_connection* c, int ev, void* ev_data, void* fn_data) {
 2 if (ev == MG_EV_HTTP_MSG) {
 3 struct mg_http_message* hm = (struct mg_http_message*)ev_data;
 4 auto pUri = strstr(hm->uri.ptr, "/zhuzhu/");
 5 if (pUri)
 6 {
 7 //Get 入口
 8 if (strstr(hm->method.ptr, "GET"))
 9 {
10 
11 }
12 else if (strstr(hm->method.ptr, "POST"))
13 {
14 
15 }
16 else
17 mg_http_reply(c, 405, nullptr, "");
18 }
19 else if (hm->uri.len <= 1) {
20 struct mg_http_serve_opts opts = { 0 };
21 opts.root_dir = "."; // Serve
22 mg_http_serve_dir(c, (mg_http_message*)ev_data, &opts); // static content
23 }
24 else
25 mg_http_reply(c, 404, nullptr, "");
26 }
27 }
28 
29 void ThreadProcForHTTP(DWORD_PTR wparam, uint32_t lparam)
30 {
31 auto pThis = (CAppService*)wparam;
32 mg_mgr_init(&pThis->m_mg_mgr);
33 char url[128] = { 0 };
34 sprintf_s(url, 128, "http://0.0.0.0:%d", lparam);
35 auto pConn = mg_http_listen(&pThis->m_mg_mgr, url, fn, nullptr);
36 if (pConn)do { mg_mgr_poll(&pThis->m_mg_mgr, 50); } while (pThis->m_bWrok);//50ms轮训一次
37 mg_mgr_free(&pThis->m_mg_mgr);
38 pThis->m_bWrok = false;
39 }

 

posted on 2023-03-14 11:22  Sam.Richard  阅读(209)  评论(0编辑  收藏  举报

导航