Created
July 14, 2020 04:38
-
-
Save nliviu/284629802715ddfbc334877228fc3ee4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "mgos.h" | |
#include "mgos_rpc.h" | |
struct rpc_ipinfo_ctx { | |
struct mg_rpc_request_info *ri; | |
struct mbuf response; | |
}; | |
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data, | |
void *cb_arg) { | |
struct rpc_ipinfo_ctx *ctx = (struct rpc_ipinfo_ctx *) cb_arg; | |
switch (ev) { | |
case MG_EV_CONNECT: | |
if (*(int *) ev_data != 0) { | |
mg_rpc_send_errorf(ctx->ri, 400, "Connection error"); | |
} | |
break; | |
case MG_EV_HTTP_REPLY: { | |
nc->flags |= MG_F_CLOSE_IMMEDIATELY; | |
struct http_message *msg = (struct http_message *) ev_data; | |
if ((msg != NULL) && (msg->body.p != NULL) && (msg->body.len != 0)) { | |
LOG(LL_INFO, ("body: \"%.*s\"", msg->body.len, msg->body.p)); | |
mbuf_append(&ctx->response, msg->body.p, msg->body.len); | |
mg_rpc_send_responsef(ctx->ri, "%.*s", ctx->response.len, | |
ctx->response.buf); | |
} | |
break; | |
} | |
case MG_EV_CLOSE: | |
LOG(LL_INFO, ("Connection closed.")); | |
if (ctx != NULL) { | |
mbuf_free(&ctx->response); | |
free(ctx); | |
} | |
break; | |
default: | |
break; | |
} | |
} | |
static void rpc_ipinfo_handler(struct mg_rpc_request_info *ri, | |
void *cb_arg __attribute__((unused)), | |
struct mg_rpc_frame_info *fi | |
__attribute__((unused)), | |
struct mg_str args) { | |
char *ip = NULL; | |
if (json_scanf(args.p, args.len, ri->args_fmt, &ip) != 1) { | |
mg_rpc_send_errorf(ri, 400, "Missing ip parameter"); | |
return; | |
} | |
struct rpc_ipinfo_ctx *ctx = | |
(struct rpc_ipinfo_ctx *) calloc(1, sizeof(*ctx)); | |
ctx->ri = ri; | |
mbuf_init(&ctx->response, 0); | |
char url[64]; | |
snprintf(url, sizeof(url), "https://ipinfo.io/%s/json", ip); | |
struct mg_mgr *mgr = mgos_get_mgr(); | |
struct mg_connection *c = | |
mg_connect_http(mgr, ev_handler, ctx, url, NULL, NULL); | |
if (c == NULL) { | |
mg_rpc_send_errorf(ri, 400, "Connection error"); | |
} | |
} | |
enum mgos_app_init_result mgos_app_init(void) { | |
struct mg_rpc *c = mgos_rpc_get_global(); | |
mg_rpc_add_handler(c, "IPinfo", "{ip:%Q}", rpc_ipinfo_handler, NULL); | |
return MGOS_APP_INIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment