To create a simple C++ wrapper around libcurl for fetching the current temperature based on longitude and latitude from weatherapi.com, we need to ensure that the wrapper is efficient, handles errors with exceptions, and processes chunks correctly. Below is an example implementation that meets these requirements.
First, ensure you have libcurl installed on your system. You can install it using a package manager like apt on Ubuntu:
sudo apt-get install libcurl4-openssl-dev
Here is the C++ code for the wrapper:
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <stdexcept>
#include <nlohmann/json.hpp>
class WeatherAPI {
public:
WeatherAPI(const std::string& apiKey, double latitude, double longitude)
: apiKey(apiKey), latitude(latitude), longitude(longitude) {
if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) {
throw std::runtime_error("Failed to initialize libcurl");
}
}
~WeatherAPI() {
curl_global_cleanup();
}
double getCurrentTemperature() {
CURL* curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
if (!curl) {
throw std::runtime_error("Failed to initialize CURL");
}
std::string url = "http://api.weatherapi.com/v1/current.json?key=" + apiKey +
"&q=" + std::to_string(latitude) + "," + std::to_string(longitude);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
curl_easy_cleanup(curl);
throw std::runtime_error("CURL failed: " + std::string(curl_easy_strerror(res)));
}
curl_easy_cleanup(curl);
try {
auto json = nlohmann::json::parse(readBuffer);
return json["current"]["temp_c"];
} catch (const nlohmann::json::parse_error& e) {
throw std::runtime_error("Failed to parse JSON response: " + std::string(e.what()));
}
}
private:
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
std::string apiKey;
double latitude;
double longitude;
};
int main() {
try {
WeatherAPI weatherAPI("YOUR_API_KEY", 37.7749, -122.4194); // Example coordinates for San Francisco
double temperature = weatherAPI.getCurrentTemperature();
std::cout << "Current temperature: " << temperature << " °C" << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
Explanation:
-
Initialization and Cleanup:
- The
WeatherAPI class initializes libcurl in the constructor and cleans it up in the destructor.
- The
curl_global_init and curl_global_cleanup functions are used to initialize and clean up the libcurl library.
-
Error Handling:
- Errors are handled using exceptions. If
libcurl initialization fails or if the curl_easy_perform call fails, an exception is thrown.
- JSON parsing errors are also handled with exceptions.
-
Chunk Processing:
- The
WriteCallback function is used to append data chunks to a std::string buffer. This ensures that the data is processed correctly in chunks.
-
JSON Parsing:
- The
nlohmann/json library is used to parse the JSON response. This library is lightweight and easy to use.
- The temperature is extracted from the JSON response and returned.
Dependencies:
- libcurl: For making HTTP requests.
- nlohmann/json: For parsing JSON responses. You can include this library by downloading it from nlohmann/json GitHub repository or using a package manager like
vcpkg.
Compilation:
To compile the code, you need to link against libcurl and include the nlohmann/json header. Here is an example compilation command:
g++ -std=c++17 -o weatherapi weatherapi.cpp -lcurl
Make sure to replace "YOUR_API_KEY" with your actual API key from weatherapi.com.
This implementation is efficient, handles errors gracefully, and processes chunks correctly, meeting the requirements specified.