[Webserver]httplib webserver+client(MacOS,Linux)

👉🏻 웹개발이 아닌 일반 c++ 앱 개발시 웹서버와 통신하는 방법에 대한 설명입니다.
This explains how to communicate with a web server when developing general C++ apps, not web development.

👉🏻 http,https,json 파싱에 대한 부분을 다룹니다.
This covers http, https, and JSON parsing.

👉🏻 방화벽 설정이나 https설정부분은 이전 게시물을 참고 하세요.
Please refer to the previous post for firewall and HTTPS settings.

👉🏻Http 서버(MacOS에서 테스트)
HTTP server (tested on MacOS)

✔️ 코드 / code

#include "httplib.h"
#include <iostream>

int main() {
    httplib::Server svr;

    svr.Get("/", [](const httplib::Request&, httplib::Response& res) {
        res.set_content("Hello HTTP", "text/plain");
    });

    std::cout << "Listening on http://0.0.0.0:5080\n";
    svr.listen("0.0.0.0", 5080);
}

✔️ 컴파일 / Compiling

g++ -o http_server http_server.cpp -std=c++11 -pthread

✔️ 실행 / run

./http_server
http server

👉🏻Http 클라이언트 / Http client

✔️ 코드 / code

#include "httplib.h"
#include <iostream>

int main() {
    httplib::Client cli("http://127.0.0.1:5080");

    if (auto res = cli.Get("/")) {
        std::cout << "status: " << res->status << "\n";
        std::cout << "body: " << res->body << "\n";
    } else {
        std::cerr << "request failed\n";
    }
}

✔️ 컴파일 / Compiling

g++ -o http_client http_client.cpp -std=c++11 -pthread

✔️ 실행 / run

./http_client
http client

👉🏻 Https 서버(Linux에서 테스트)
HTTPS Server (Tested on Linux)

⭐️ libssl-dev 설치되어 있어야 합니다
libssl-dev must be installed.

sudo apt install libssl-dev

✔️ 코드 / Code

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "../httplib.h"
#include <iostream>

int main() {
    httplib::SSLServer svr("./fullchain.pem", "./privkey.pem");

    if (!svr.is_valid()) {
        std::cerr << "SSL server setup failed\n";
        return 1;
    }

    svr.Get("/", [](const httplib::Request&, httplib::Response& res) {
        res.set_content("<h1>Hello HTTPS</h1>", "text/html");
    });

    std::cout << "Listening on https://0.0.0.0:5080\n";
    svr.listen("0.0.0.0", 5080);
}

✔️ 컴파일 / Compiling

g++ https_server.cpp -o https_server -std=c++11 -pthread -lssl -lcrypto

✔️ 실행 / Run

./https_server
https server

👉🏻Https 클라이언트 / Https Client

✔️ 코드 / Code

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "../httplib.h"
#include <iostream>

int main() {
    httplib::Client cli("https://yourhost.domain.org:5080");

    if (auto res = cli.Get("/")) {
        std::cout << res->status << "\n";
        std::cout << res->body << "\n";
    } else {
        std::cerr << "request failed\n";
    }
}

✔️ 컴파일 / Compiling

g++ https_client.cpp -o https_client -std=c++11 -pthread -lssl -lcrypto

✔️ 실행 / Run

./https_client
https client

👉🏻 Https Json(Linux에서 테스트)
HTTPS JSON (Tested on Linux)

✔️ Linux

sudo apt update
sudo apt install nlohmann-json3-dev

✔️ 설치 경로 / Installation path

/usr/include/nlohmann/json.hpp

✔️ MacOS

brew install nlohmann-json

✔️ 설치경로 / Installation path

/opt/homebrew/include/nlohmann/json.hpp

✔️ 생성된 json.http파일을 작업중인 디렉토리로 복사합니다.
Copy the generated json.http file to the working directory.

sudo cp /usr/include/nlohmann/json.hpp ./

✔️ 서버코드 / Server Code

— server.cpp

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "../httplib.h"
#include "json.hpp"
#include <iostream>

using json = nlohmann::json;

int main() {
    httplib::SSLServer svr("./fullchain.pem", "./privkey.pem");

    if (!svr.is_valid()) {
        std::cerr << "SSL server setup failed\n";
        return 1;
    }

    svr.Get("/api", [](const httplib::Request&, httplib::Response& res) {
        json j = {
            {"ok", true},
            {"msg", "hello"},
            {"value", 123}
        };
        res.set_content(j.dump(), "application/json");
    });

    std::cout << "Listening on https://0.0.0.0:5080\n";
    svr.listen("0.0.0.0", 5080);
}

✔️ 클라이언트 코드 / Client Code

— client.cpp

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "../httplib.h"
#include "json.hpp"
#include <iostream>

using json = nlohmann::json;

int main() {
    httplib::Client cli("https://yourhost.domain.org:5080");

    if (auto res = cli.Get("/api")) {
        json j = json::parse(res->body);
        std::cout << "ok: " << j["ok"] << "\n";
        std::cout << "msg: " << j["msg"] << "\n";
        std::cout << "value: " << j["value"] << "\n";
    } else {
        std::cerr << "request failed\n";
    }
}

✔️ 컴파일 / Compiling

— Linux

g++ -o server.cpp -std=c++11 -pthread -lssl -lcrypto
g++ -o client.cpp -std=c++11 -pthread -lssl -lcrypto

— MacOS

g++ server.cpp -o server -std=c++11 -pthread \
  -I/opt/homebrew/opt/openssl@3/include \
  -L/opt/homebrew/opt/openssl@3/lib \
  -lssl -lcrypto -framework Security -framework CoreFoundation

g++ client.cpp -o client -std=c++11 -pthread \
  -I/opt/homebrew/opt/openssl@3/include \
  -L/opt/homebrew/opt/openssl@3/lib \
  -lssl -lcrypto -framework Security -framework CoreFoundation

✔️ 실행 / Run

— 서버 클라이언트를 서로 다른 터미널에서 실행합니다.
Run the server and client in different terminals.

./server # server
./client # client
https json server
https json client

Leave a Reply