TFT Support - 1 본문
Riot에서 제공하는 api를 가지고 무언가 만들어보고 싶었다.
이번에도 c++로 만들 예정이며
단일 책임 원칙을 지켜가며 설계를 해보고 싶었다.
일단 API를 가져오는 클래스부터 간단하게 구현하기로 했다.
해당 디렉터리 구조를 가지고 있고
tasks.json파일을 수정하였다.
#ifndef APIMANAGER_H
#define APIMANAGER_H
#include <string>
#include <curl/curl.h>
class APIManager{
private:
std::string apiEndpoint;
public:
APIManager(const std::string& endpoint);
void fetchData();
private:
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void* userp);
};
#endif // APIMANAGER_H
APIManager.h
#ifndef
#define
#endif
를 통해 헤더 가드를 해준다.
이는 중복 포함으로 인한 컴파일 오류를 방지한다.
클래스 내부에서 선언하기 위한 apiEndpoint를 만들어주었다.
APIManager(const std::string& endpoint);
생성자를 통해 apiEndpoint에 데이터가 들어갈 것이다.
void fetchData(); 에서 curl을 통해 api를 받아오고 출력해 준다.
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void* userp);
이 부분은 curl을 날리고 데이터를 받기 위한 함수이다.
꼭 함수의 형식과 반환형식을 지켜주어야 libcurl의 데이터를 전달받을 수 있다.
#include "APIManager.h"
#include <iostream>
#include <curl/curl.h>
// 정적 멤버 변수 초기화
size_t APIManager::WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
APIManager::APIManager(const std::string& endpoint) : apiEndpoint(endpoint) {
// 생성자에서 초기화할 것이 있다면 여기에 추가
}
void APIManager::fetchData() {
CURL* curl;
CURLcode res;
std::string readBuffer;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, apiEndpoint.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// HTTP 요청 수행
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
std::cout << "Fetched Data: " << readBuffer << std::endl;
// 여기서 readBuffer에 있는 데이터를 다른 곳에 저장하거나 처리할 수 있습니다.
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
}
APIManager.cpp
WriteCallback은 전달받은 데이터를 userp에 추가하는 코드이다.
해당 함수를 만들어줘야 제대로 데이터를 받아올 수 있다.
그다음 생성자 코드이다.
APIManager::APIManager(const std::string& endpoint) : apiEndpoint(endpoint) {
// 생성자에서 초기화할 것이 있다면 여기에 추가
}
클래스의 인스턴스가 만들어질 때 curl을 매개변수로 넣으면
최종적으로 apiEndpoint에 들어가게 된다.
다음 fetchDate()를 본다.
CURL* curl;
CURLcode res;
std::string readBuffer;
curl은 'libcurl' 핸들러를 가리키는 포인터이다.
res는 'libcurl' 함수의 반환 값을 저장하는 변수이다.
readBuffer는 http 응답 데이터를 저장할 문자열 버퍼이다.
curl_global_init(CURL_GLOBAL_DEFAULT);
'libcurl'을 사용하기 전에 전역적으로 초기화한다.
이 함수는 'libcurl' 라이브러리의 여러 기능을 초기화한다.
curl = curl_easy_init();
새로운 'CURL'핸들러를 초기화한다.
curl_easy_setopt(curl, CURLOPT_URL, apiEndpoint.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
요청할 URL을 설정해 준다.
다음은 libcurl이 데이터를 수신할 때 호출할 콜백 함수를 설정한다.
콜백 함수가 데이터를 처리하고 저장할 변수를 설정한다.
res = curl_easy_perform(curl);
설정된 옵션을 바탕으로 http요청을 수행하고 결과 코드를 저장한다.
curl_easy_cleanup(curl);
curl_global_cleanup();
curl핸들러를 정리하고 libcurl을 전역적으로 정리한다.
#include "APIManager.h"
using namespace std;
int main() {
APIManager apiManager("https://asia.api.riotgames.com/tft/match/v1/matches/KR_7116810596?api_key=???"); // 실제 API 엔드포인트로 변경
apiManager.fetchData();
return 0;
}
메인함수이다.
매개변수로 URL을 써준다.
내가 마지막으로 경기했던 데이터들이 출력한다.
해당 쿼리들의 자세한 키값들은 추후 찾아볼 예정이다.
'개발 > 개인공부' 카테고리의 다른 글
TFT Support - 3 (0) | 2024.07.02 |
---|---|
TFT Support - 2 (0) | 2024.06.26 |
리눅스 멀티스레드 파일 공유 프로그램 - 10(완) (0) | 2024.06.16 |
리눅스 멀티스레드 파일 공유 프로그램 - 9 (1) | 2024.06.14 |
리눅스 멀티스레드 파일 공유 프로그램 - 8 (0) | 2024.06.12 |