Here's a minimal, zero-overhead C++20 wrapper around libcurl to fetch the current temperature using longitude and latitude from weatherapi.com , with:
No unnecessary copies
Zero overhead abstractions
Exception-based error handling
Streaming chunk processing
RAII-style resource management
✅ Prerequisites
Make sure you have:
libcurl installed
Compile with: -std=c++20 -lcurl
📦 Code: weather_client.hpp
cpp Copy code
// weather_client.hpp
#pragma once
#include <curl/curl.h>
#include <stdexcept>
#include <string>
#include <string_view>
#include <memory>
#include <sstream>
#include <format>
class WeatherClient {
public:
explicit WeatherClient(std::string_view apiKey);
~WeatherClient();
// Deleted copy operations
WeatherClient(const WeatherClient&) = delete;
WeatherClient& operator=(const WeatherClient&) = delete;
// Default move operations
WeatherClient(WeatherClient&&) noexcept = default;
WeatherClient& operator=(WeatherClient&&) noexcept = default;
// Fetches current temperature by coordinates
double getCurrentTemperature(double lat, double lon);
private:
std::string _apiKey;
struct CurlDeleter {
void operator()(CURL* handle) const { curl_easy_cleanup(handle); }
};
std::unique_ptr<CURL, CurlDeleter> _curl;
static size_t writeCallback(char* data, size_t size, size_t nmemb, std::ostringstream* buffer);
};
🔧 Implementation: weather_client.cpp
cpp Copy code
// weather_client.cpp
#include "weather_client.hpp"
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <json.hpp> // Use nlohmann/json (single include)
using json = nlohmann::json;
WeatherClient::WeatherClient(std::string_view apiKey)
: _apiKey(apiKey), _curl(curl_easy_init(), CurlDeleter()) {
if (!_curl) {
throw std::runtime_error("Failed to initialize CURL");
}
// Global init only once per app (safe here for simplicity)
static bool globalInitDone = []() {
CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
return res == CURLE_OK;
}();
if (!globalInitDone) {
throw std::runtime_error("Failed to initialize global CURL");
}
}
WeatherClient::~WeatherClient() = default;
size_t WeatherClient::writeCallback(char* data, size_t size, size_t nmemb, std::ostringstream* buffer) {
const size_t realsize = size * nmemb;
buffer->write(data, realsize);
return realsize;
}
double WeatherClient::getCurrentTemperature(double lat, double lon) {
std::ostringstream responseBuffer;
std::string url = std::format(
"https://api.weatherapi.com/v1/current.json?key={}&q={},{}", _apiKey, lat, lon);
curl_easy_setopt(_curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(_curl.get(), CURLOPT_WRITEFUNCTION, &WeatherClient::writeCallback);
curl_easy_setopt(_curl.get(), CURLOPT_WRITEDATA, &responseBuffer);
curl_easy_setopt(_curl.get(), CURLOPT_FOLLOWLOCATION, 1L); // Follow redirects
CURLcode res = curl_easy_perform(_curl.get());
if (res != CURLE_OK) {
throw std::runtime_error(std::format("cURL error: {}", curl_easy_strerror(res)));
}
long http_code = 0;
curl_easy_getinfo(_curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
if (http_code != 200) {
throw std::runtime_error(std::format("HTTP error code: {}", http_code));
}
// Parse JSON
try {
auto jsonResponse = json::parse(responseBuffer.view());
return jsonResponse.at("current").at("temp_c").get<double>();
} catch (const json::exception& e) {
throw std::runtime_error(std::format("JSON parse error: {}", e.what()));
}
}
🧪 Example Usage
cpp Copy code
#include "weather_client.hpp"
#include <iostream>
int main() {
try {
WeatherClient client("YOUR_API_KEY_HERE");
double lat = 40.7128; // New York
double lon = -74.0060;
double temp = client.getCurrentTemperature(lat, lon);
std::cout << "Current temperature: " << temp << "°C\n";
} catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << "\n";
}
}
📦 Dependencies
libcurl : Install via your system package manager or vcpkg/conan.
nlohmann/json : Single-header JSON library for C++. Include it via:
bash Copy code
# Using vcpkg
vcpkg install nlohmann-json
Or just drop in the header from GitHub .
⚙️ Compilation Command
bash Copy code
g++ -std=c++20 -Wall -Wextra -O2 main.cpp weather_client.cpp -o weather_app -lcurl
✅ Features Summary
Feature Implemented No copies ✅ Zero overhead ✅ RAII + unique_ptr Exception safety ✅ Chunked streaming ✅ via callback JSON parsing ✅ via nlohmann/json Moveable ✅ Non-copyable ✅ deleted copy ops
Let me know if you want:
Async support (e.g., std::future)
Support for other weather services
Unit tests or mocks
Custom allocators or embedded-friendly options
Happy coding! ☀️🌧️