curl.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #pragma once
  2. #include <cstdlib>
  3. #include <sstream>
  4. #include <string>
  5. #include <string_view>
  6. #include <curl/curl.h>
  7. #include <jvalidate/adapter.h>
  8. #include <jvalidate/forward.h>
  9. #include <jvalidate/uri.h>
  10. namespace jvalidate {
  11. inline size_t transfer_to_buffer(char * data, size_t size, size_t nmemb, void * userdata) {
  12. std::stringstream & ss = *static_cast<std::stringstream *>(userdata);
  13. size_t const actual_size = size * nmemb;
  14. ss << std::string_view(data, actual_size);
  15. return actual_size;
  16. }
  17. template <typename JSON>
  18. bool curl_get(jvalidate::URI const & uri, JSON & out, std::string & error) noexcept {
  19. using jvalidate::adapter::load_file;
  20. using jvalidate::adapter::load_stream;
  21. if (uri.scheme().starts_with("http")) {
  22. std::stringstream ss;
  23. if (CURL * curl = curl_easy_init(); curl) {
  24. curl_easy_setopt(curl, CURLOPT_URL, uri.c_str());
  25. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  26. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ss);
  27. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &transfer_to_buffer);
  28. CURLcode const res = curl_easy_perform(curl);
  29. curl_easy_cleanup(curl);
  30. if (res == CURLE_OK) {
  31. return load_stream(ss, out, error);
  32. }
  33. }
  34. return false;
  35. }
  36. if (uri.scheme() == "file") {
  37. return load_file(uri.resource(), out, error);
  38. }
  39. error = "unknown scheme";
  40. return false;
  41. }
  42. }