備忘録

備忘録

mongooseを利用してHTTPサーバを構築する方法

Ⅰ. はじめに

タイトルの通り「mongooseを利用してHTTPサーバを構築する方法」です。

Ⅱ. やり方

1. サンプルプログラムを書く
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
extern "C" {
#include <mongoose.h>
}

static void fn(struct mg_connection* c, int ev, void* ev_data, void* fn_data) {
  if (ev == MG_EV_HTTP_MSG) {
    struct mg_http_message* hm = (struct mg_http_message*)ev_data;
    if (mg_http_match_uri(hm, "/test1")) {
      // "ok"を返す
      mg_http_reply(c, 200, "", "ok");
    }
    else if (mg_http_match_uri(hm, "/test2")) {
      // "helloworld"を返す
      std::string str("helloworld");
      mg_printf(c, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n", str.size());
      mg_send(c, str.c_str(), str.size());
    }
    else if (mg_http_match_uri(hm, "/test3")) {
      // bodyをそのまま返す
      mg_printf(c, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n", hm->body.len);
      mg_send(c, hm->body.ptr, hm->body.len);
    }
    else if (mg_http_match_uri(hm, "/test4")) {
      // クエリパラメータを取得する
      char buffer[16] = { 0 };
      auto size = mg_http_get_var(&hm->query, "param001", buffer, sizeof(buffer));
      std::string param001(buffer, size);

      mg_printf(c, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n", param001.size());
      mg_send(c, param001.c_str(), param001.size());
    }
  }
}

int main() {
  // Initialise event manager
  struct mg_mgr mgr;
  mg_mgr_init(&mgr);

  // Create HTTP listener
  mg_http_listen(&mgr, "http://0.0.0.0:80", fn, NULL);

  // Infinite event loop
  while (true) {
    mg_mgr_poll(&mgr, 1000);
  }

  return 0;
}

実行結果1

GET http://127.0.0.1/test1 HTTP/1.1
Host: 127.0.0.1
HTTP/1.1 200 OK
Content-Length: 2

ok

実行結果2

GET http://127.0.0.1/test2 HTTP/1.1
Host: 127.0.0.1
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 10

helloworld

実行結果3

POST http://127.0.0.1/test3 HTTP/1.1
Host: 127.0.0.1
Content-Length: 11

HelloWorld!
HTTP/1.1 200 OK
Content-Length: 11

HelloWorld!

実行結果4

GET http://127.0.0.1/test4?param001=helloworld HTTP/1.1
Host: 127.0.0.1
HTTP/1.1 200 OK
Content-Length: 10

helloworld