int m2x_client_get(m2x_context *ctx, const char *path, char **out) { curl_write_context *write_ctx; char *url; CURLcode res; write_ctx = create_write_context(ctx); url = create_url(ctx, path); curl_easy_reset(ctx->curl); curl_easy_setopt(ctx->curl, CURLOPT_URL, url); m2x_free(url); if (ctx->verbose) { curl_easy_setopt(ctx->curl, CURLOPT_VERBOSE, 1); } curl_easy_setopt(ctx->curl, CURLOPT_HTTPHEADER, ctx->headers); curl_easy_setopt(ctx->curl, CURLOPT_WRITEDATA, write_ctx); curl_easy_setopt(ctx->curl, CURLOPT_WRITEFUNCTION, write_callback); res = curl_easy_perform(ctx->curl); if (res != CURLE_OK) { fprintf(stderr, "GET failed: %s\n", curl_easy_strerror(res)); release_write_context(write_ctx, 1); return res; } if (out != NULL) { *out = write_ctx->p; } else { m2x_free(write_ctx->p); } release_write_context(write_ctx, 0); return res; }
static void release_write_context(curl_write_context* write_ctx, int release_buf) { if (release_buf) { m2x_free(write_ctx->p); } m2x_free(write_ctx); }
m2x_response m2x_chart_delete(m2x_context *ctx, const char *chart_id) { int status; char *path, *out = NULL; path = m2x_internal_create_format_string(ctx, "/charts/%s", chart_id); status = m2x_client_delete(ctx, path, NULL, &out); m2x_free(path); return m2x_make_response(ctx, status, out); }
m2x_response m2x_chart_list(m2x_context *ctx, const char *query) { int status; char *path, *out = NULL; path = m2x_internal_create_query_path(ctx, "/charts", query); status = m2x_client_get(ctx, path, &out); m2x_free(path); return m2x_make_response(ctx, status, out); }
m2x_response m2x_job_view(m2x_context *ctx, const char *job_id) { int status; char *path, *out = NULL; path = m2x_internal_create_format_string(ctx, "/jobs/%s", job_id); status = m2x_client_get(ctx, path, &out); m2x_free(path); return m2x_make_response(ctx, status, out); }
m2x_context *m2x_open(const char* key) { m2x_context *ctx; char* str; ctx = (m2x_context *) m2x_malloc(NULL, sizeof(m2x_context)); memset(ctx, 0, sizeof(m2x_context)); ctx->verbose = 0; ctx->curl = curl_easy_init(); ctx->headers = curl_slist_append(ctx->headers, "User-Agent: M2X/0.0.1 (C libcurl)"); ctx->headers = curl_slist_append(ctx->headers, "Content-Type: application/json"); str = (char *) m2x_malloc(ctx, (12 + strlen(key)) * sizeof(char)); strcpy(str, "X-M2X-KEY: "); strcpy(str + 11, key); ctx->headers = curl_slist_append(ctx->headers, str); m2x_free(str); return ctx; }
void m2x_close(m2x_context *ctx) { curl_slist_free_all(ctx->headers); curl_easy_cleanup(ctx->curl); m2x_free(ctx); }