forked from ground/ground
53 lines
1.5 KiB
C++
53 lines
1.5 KiB
C++
#include "ground_lib.h"
|
|
|
|
#include <cpr/cpr.h>
|
|
#include <cpr/interface.h>
|
|
#include <fstream>
|
|
|
|
void error(std::string status) {
|
|
std::cout << "Request error: " << status << std::endl;
|
|
}
|
|
|
|
GroundValue simpleRequest(GroundValue* args, int arg_count) {
|
|
VALIDATE_ARGS_1(GROUND_STRING);
|
|
|
|
cpr::Response r = cpr::Get(cpr::Url(GET_STRING(args[0])));
|
|
|
|
if (!(r.status_code >= 200 && r.status_code < 300)) {
|
|
error("Non zero HTTP code " + std::to_string(r.status_code));
|
|
return ground_string_val("Error code " + std::to_string(r.status_code));
|
|
}
|
|
|
|
return ground_string_val(r.text);
|
|
}
|
|
|
|
GroundValue saveContents(GroundValue* args, int arg_count) {
|
|
VALIDATE_ARGS_2(GROUND_STRING, GROUND_STRING);
|
|
|
|
std::ofstream file(GET_STRING(args[1]), std::ios::binary);
|
|
|
|
if (file.good()) {
|
|
cpr::Response r = cpr::Download(file, cpr::Url{GET_STRING(args[0])});
|
|
|
|
if (!(r.status_code >= 200 && r.status_code < 300)) {
|
|
error("Non zero HTTP code " + std::to_string(r.status_code));
|
|
return GROUND_BOOL_VAL(false);
|
|
}
|
|
} else {
|
|
error(std::string("Cannot open file ") + GET_STRING(args[1]) + " for writing");
|
|
return GROUND_BOOL_VAL(false);
|
|
}
|
|
|
|
return GROUND_BOOL_VAL(true);
|
|
}
|
|
|
|
GROUND_LIBRARY_INTERFACE()
|
|
|
|
GROUND_LIBRARY_INIT()
|
|
REGISTER_GROUND_FUNCTION(simpleRequest);
|
|
REGISTER_GROUND_FUNCTION(saveContents);
|
|
GROUND_LIBRARY_INIT_END()
|
|
|
|
GROUND_LIBRARY_CLEANUP()
|
|
GROUND_LIBRARY_CLEANUP_END()
|