63 lines
1.6 KiB
C
63 lines
1.6 KiB
C
#include <http.h>
|
|
#include <stdio.h>
|
|
|
|
#if INTERFACE
|
|
|
|
struct Http {
|
|
Connection connection;
|
|
};
|
|
|
|
#endif
|
|
|
|
int http_get(EV_P_ Http *http, const char *servername, const char *path) {
|
|
struct tls_config *config;
|
|
|
|
config = tls_config_new();
|
|
if (connection_open(EV_DEFAULT_ & http->connection, config, servername,
|
|
"https")) {
|
|
goto err_connection_open;
|
|
}
|
|
buffer_printf(connection_write_buf(&http->connection),
|
|
"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n",
|
|
path, servername);
|
|
connection_set_failure_cb(&http->connection, error_cb);
|
|
connection_set_cb(&http->connection, http_get_cb);
|
|
connection_write_some(EV_A_ & http->connection);
|
|
tls_config_free(config);
|
|
return 0;
|
|
|
|
err_connection_open:
|
|
tls_config_free(config);
|
|
return -1;
|
|
}
|
|
|
|
static void error_cb(EV_P_ Connection *connection) {
|
|
connection_close(EV_A_ connection);
|
|
ev_break(EV_A_ EVBREAK_ALL);
|
|
}
|
|
|
|
static void http_get_cb(EV_P_ Connection *connection) {
|
|
if (buffer_size(connection_write_buf(connection))) {
|
|
connection_write_some(EV_A_ connection);
|
|
return;
|
|
}
|
|
connection_set_cb(connection, http_response_cb);
|
|
connection_read_some(EV_A_ connection);
|
|
}
|
|
|
|
static void http_response_cb(EV_P_ Connection *connection) {
|
|
Buffer *read_buf;
|
|
size_t n;
|
|
|
|
read_buf = connection_read_buf(connection);
|
|
n = buffer_size(read_buf);
|
|
if (n) {
|
|
fwrite(buffer_data(read_buf), n, 1, stdout);
|
|
buffer_consume(read_buf, n);
|
|
connection_read_some(EV_A_ connection);
|
|
return;
|
|
}
|
|
connection_close(EV_A_ connection);
|
|
ev_break(EV_A_ EVBREAK_ALL);
|
|
}
|