mosheng 发表于 2024-12-9 19:27:15

mongoose轻量的 C 语言编写的 HTTP 服务器,大小仅214KB

> **引用mongoose7.16**:https://github.com/cesanta/mongoose/tree/7.16
> **编译好的exe文件仅214KB**

![](https://pic.imgdb.cn/item/6756d21ad0e0a243d4e0a99a.png)

### 1、克隆到本地

```
git clone https://github.com/cesanta/mongoose.git
```

---

### 2、打开visual studio,新建C++空项目

![](https://pic.imgdb.cn/item/6756d23dd0e0a243d4e0a9b8.png)

#### 头文件添加现有项,克隆下来的mongoose.h

#### 源文件添加现有项,克隆下来的mongoose.c

![](https://pic.imgdb.cn/item/6756d252d0e0a243d4e0a9bd.png)
---

### 3、解决方案右键属性,设置VC++目录->包含目录,添加你克隆下来的目录点确定

![](https://pic.imgdb.cn/item/6756d26dd0e0a243d4e0a9c2.png)
---

### 4、C/C++ -> 代码生成 -> 运行库,设置为MT

---
![](https://pic.imgdb.cn/item/6756d287d0e0a243d4e0a9c8.png)

### 5、语言设置为最新

![](https://pic.imgdb.cn/item/6756d2a0d0e0a243d4e0a9d0.png)
---

### 6、main.cpp代码

```cpp
#include "mongoose.h"   // To build, run: cc main.c mongoose.c
#include <stdio.h>      // For printf
#include <stdlib.h>   // For _fullpath

// HTTP server event handler function
static void ev_handler(struct mg_connection* c, int ev, void* ev_data) {
    if (ev == MG_EV_HTTP_MSG) {
      struct mg_http_message* hm = (struct mg_http_message*)ev_data;

      // 如果请求的是 /api/time/get 路径,则返回当前时间
      if (mg_match(hm->uri, mg_str("/api/time/get"), NULL)) {
            mg_http_reply(c, 200, "", "{%m:%lu}\n", MG_ESC("time"), time(NULL));
      }
      // 如果请求的是 /hello 路径,则返回自定义响应
      else if (mg_match(hm->uri, mg_str("/hello"), NULL)) {
            mg_http_reply(c, 200, "Content-Type: text/html\r\n",
                "<html><body>Hello, World!</body></html>");
      }
      // 对于其他资源,尝试从磁盘加载静态文件
      else {
            struct mg_http_serve_opts opts = { .root_dir = "./web_root/" };

            // 获取并打印 root_dir 的完整路径
            char full_path = "";
            if (_fullpath(full_path, opts.root_dir, sizeof(full_path)) != NULL) {
                printf("Serving static files from directory: %s\n", full_path);
            }
            else {
                printf("Failed to get the full path of root_dir.\n");
            }

            mg_http_serve_dir(c, hm, &opts);
      }
    }
}

int main(void) {
    struct mg_mgr mgr;// Declare event manager
    mg_mgr_init(&mgr);// Initialise event manager
    mg_http_listen(&mgr, "http://0.0.0.0:8000", ev_handler, NULL);// Setup listener
    printf("Starting server on port 8000...\n");

    for (;;) {          // Run an infinite event loop
      mg_mgr_poll(&mgr, 1000);
    }

    mg_mgr_free(&mgr);// Cleanup resources
    return 0;
}
```

---

### 7、编译出来后,把网站文件放在web_root文件夹内

![](https://pic.imgdb.cn/item/6756d2bed0e0a243d4e0a9d7.png)
---

### 8、运行效果图

![](https://pic.imgdb.cn/item/6756d2bdd0e0a243d4e0a9d6.png)

itniao 发表于 2026-2-16 21:03:47

大神真的是手把手的教的呀!!

A丶 发表于 2025-2-7 13:10:16

谢谢大佬分享,学到了很多

Cc网络 发表于 2024-12-13 08:57:03

顶一个证明我存在

tes124259 发表于 2024-12-9 19:35:26

空白的???
页: [1]
查看完整版本: mongoose轻量的 C 语言编写的 HTTP 服务器,大小仅214KB