[4] Nginx Server Setup - Writing a Drogon Test API



Let's create an API using Drogon to return specific values as a test.

---

## 1. Setting up the Drogon Test Project
- Run the following command in the directory where `drogon_ctl` is installed:  
```
drogon_ctl create project testAPI
cd testAPI
```

---

## 2. Build
- The full path will be /root/drogon2/drogon/build/drogon_ctl/testAPI/build

```
mkdir build  
cd build  
cmake ..  
make  
```

---

If the following error occurs, it’s best to set the environment variable and reinstall Drogon:

```
CMake Error at /usr/share/cmake/Modules/CMakeFindDependencyMacro.cmake:76 (find_package):  
  By not providing "FindJsoncpp.cmake" in CMAKE_MODULE_PATH this project has  
  asked CMake to find a package configuration file provided by "Jsoncpp", but  
  CMake did not find one.

  Could not find a package configuration file provided by "Jsoncpp" with any  
  of the following names:

    JsoncppConfig.cmake  
    jsoncpp-config.cmake  

  Add the installation prefix of "Jsoncpp" to CMAKE_PREFIX_PATH or set  
  "Jsoncpp_DIR" to a directory containing one of the above files. If  
  "Jsoncpp" provides a separate development package or SDK, be sure it has  
  been installed.
Call Stack (most recent call first):  
  /root/drogon/build/CMakeFiles/DrogonConfig.cmake:39 (find_dependency)  
  CMakeLists.txt:31 (find_package)  
```

This issue arises from a mismatch between the paths where Drogon and Jsoncpp are installed. To resolve this:

```
** Make sure to specify the path where `jsoncpp` is located **  

export Jsoncpp_DIR=/usr/local/lib/cmake/jsoncpp  
Check the correct path using the following commands:


find / -name "jsoncpp-config.cmake" 2>/dev/null  
find / -name "JsoncppConfig.cmake" 2>/dev/null  

Once identified, set the path and reinstall following the instructions at [Framework Build Reference](https://warguss.blogspot.com/2024/11/3-nginx-c.html) under Section 2.
```

---

## 3. Creating the Controller

```
drogon_ctl create controller testAPIController  

A controller will be created in the following path:  
[root@vbox controllers] (master) $ pwd  
/root/drogon2/drogon/build/drogon_ctl/testAPI/controllers  
```


### 3-1. Source Code  
```
testAPIController.cc  

#include "testAPIController.h"

void testAPIController::handleRequest(const HttpRequestPtr& req, std::function<void(const HttpResponsePtr&)>&& callback)
{
    auto resp = HttpResponse::newHttpResponse();
    resp->setBody("Drogon Test API");
    callback(resp);
}


---
testAPIController.h  

#pragma once  
#include <drogon/HttpController.h>  

using namespace drogon;

class testAPIController : public HttpController<testAPIController>
{
public:
    METHOD_LIST_BEGIN
    // Handles GET requests to the root path
    ADD_METHOD_TO(testAPIController::handleRequest, "/myapi", Get);
    METHOD_LIST_END

    void handleRequest(const HttpRequestPtr& req, std::function<void(const HttpResponsePtr&)>&& callback);
};
```

### 3-2. Configuration Changes
Edit `/root/drogon2/drogon/build/drogon_ctl/testAPI/config.json`. Use the following structure, modifying only the port to match the NGINX proxy port.

```
"listeners": [
    {
        // address: Ip address, 0.0.0.0 by default
        "address": "0.0.0.0",
        // port: Port number
        "port": 8848,
        // https: If true, use https for security, false by default
        "https": false
    }
],
```

### 3-3. Modify main.cc
Modify to load the configuration file by editing /root/drogon2/drogon/build/drogon_ctl/testAPI/main.cc

```
#include <drogon/drogon.h>
int main() {
    // Set HTTP listener address and port
    // drogon::app().addListener("0.0.0.0", 5555);
    // Load config file
    drogon::app().loadConfigFile("../config.json");

    // drogon::app().loadConfigFile("../config.yaml");
    // Run HTTP framework, the method will block in the internal event loop
    drogon::app().run();
    return 0;
}
```

### 3-4. Rebuild
```
cd /root/drogon2/drogon/build/drogon_ctl/testAPI/build  
make  

./testAPI  # Run the application
```

## 4. Testing
Verify access via the web.

<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTHUFhr2q2H3wL3Ha1huZvMkjn1rvdydSWXcAmpvZw4Wax43v-TkPVrVtcuZSQa52q5w6nOaDkeFCwXRfH_p3EDUe7mupZkJzQ4c1P-1zR5zyePmimFHvPb9wT3tZ59nekoBrhFTBFkgdydsjIyuri5T-9QqdE6tt6BikMaSQ5uRNbl9KKPVD5r2ZH/s1600/drogon-result.PNG" style="display: block; padding: 1em 0; text-align: center; "><img alt="nginx drogon" border="0" data-original-height="228" data-original-width="699" loading="lazy" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTHUFhr2q2H3wL3Ha1huZvMkjn1rvdydSWXcAmpvZw4Wax43v-TkPVrVtcuZSQa52q5w6nOaDkeFCwXRfH_p3EDUe7mupZkJzQ4c1P-1zR5zyePmimFHvPb9wT3tZ59nekoBrhFTBFkgdydsjIyuri5T-9QqdE6tt6BikMaSQ5uRNbl9KKPVD5r2ZH/s1600-rw/drogon-result.PNG"/></a></div>
---

<!-- 목록을 표시할 HTML 컨테이너 -->
<div>
    <h3>Related Links</h3>
    <ul id="label-post-list">
        <!-- 여기에 게시물 목록이 추가됩니다 -->
    </ul>
</div>

---

<!-- 목록을 표시할 HTML 컨테이너 -->
<div>
    <h3>Recommended Link</h3>
    <ul id="label-post-list-include">
        <!-- 여기에 게시물 목록이 추가됩니다 -->
    </ul>
</div>

---



댓글

이 블로그의 인기 게시물

윤석열 계엄령 선포! 방산주 대폭발? 관련주 투자 전략 완벽 분석

대통령 퇴진운동 관련주: 방송·통신·촛불수혜주 완벽 분석

키움 OPEN API MFC 개발 (1)