Skip to content

Instantly share code, notes, and snippets.

@MagnificentPako
Created January 18, 2019 17:06
Show Gist options
  • Save MagnificentPako/ac230110b4557336d2b7f9caae9a0613 to your computer and use it in GitHub Desktop.
Save MagnificentPako/ac230110b4557336d2b7f9caae9a0613 to your computer and use it in GitHub Desktop.
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include <emojicode/runtime/Runtime.h>
#include <emojicode/s/String.h>
#include <httplib.h>
#include <string>
#include <iostream>
#include <easywsclient.hpp>
#include <easywsclient.cpp>
#include <assert.h>
#include "net.hpp"
// WS CLIENT
extern "C" WSClient* new_ws_client(s::String *uri) {
return WSClient::init(uri->stdString().c_str());
}
extern "C" void wsclient_run(WSClient *client, runtime::Callable<void, s::String*> callable) {
using easywsclient::WebSocket;
callable.retain();
WebSocket::pointer ws = WebSocket::from_url(client->uri);
assert(ws);
while(ws->getReadyState() != WebSocket::CLOSED) {
ws->poll();
ws->dispatch([callable](const std::string & msg) {
callable(s::String::init(msg.c_str()));
});
}
delete ws;
}
// HTTPS CLIENT
httplib::Headers HTTP::convert_headers() {
httplib::Headers hea;
for(std::vector<std::pair<std::string, std::string>>::iterator it = headers.begin(); it != headers.end(); ++it) {
hea.insert(*it);
}
return hea;
}
extern "C" HTTP* new_client(s::String *host, runtime::Integer port) {
return HTTP::init(host->stdString().c_str(), port);
}
extern "C" s::String* get(HTTP *http, s::String *path) {
auto headers = http->convert_headers();
auto res = http->client.Get(path->stdString().c_str(), headers);
if(res && res->status == 200) {
return s::String::init(res->body.c_str());
} else {
return s::String::init(" ");
}
}
extern "C" s::String* post(HTTP *http, s::String *path, s::String *content_type, s::String *data) {
auto headers = http->convert_headers();
auto res = http->client.Post(path->stdString().c_str(), headers,
data->stdString().c_str(),
content_type->stdString().c_str());
if(res && res->status == 200) {
return s::String::init(res->body.c_str());
} else {
std::cout << res->status << std::endl;
std::cout << res->body << std::endl;
return s::String::init(" ");
}
}
extern "C" void add_header(HTTP *http, s::String *name, s::String *content) {
http->headers.push_back(std::make_pair(name->stdString(),
content->stdString()));
}
SET_INFO_FOR(HTTP, net, 1f351)
SET_INFO_FOR(WSClient, net, 1f981) // lion
SET_INFO_FOR(WSMsg, net, 1f526) // flashlight
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment