diff --git a/README.md b/README.md index f2be734..0194816 100644 --- a/README.md +++ b/README.md @@ -352,6 +352,20 @@ curl http://127.0.0.1:8083/api/0/locations -d user=jpm -d device=5s -d format=ge curl http://127.0.0.1:8083/api/0/locations -d user=jpm -d device=5s -d from=2014-08-03 ``` +#### `q` + +Query the geo cache for a particular _lat_ and _lon_. + +``` +curl 'http://127.0.0.1:8083/api/0/q?lat=48.85833&lon=2.295' +{ + "cc": "FR", + "addr": "9 Avenue Anatole France, 75007 Paris, France", + "tst": 1441984405 +} +``` + +The reported timestamp was the time at which this cache entry was made. Note that this interface queries only -- it does not populate the cache. #### `block` diff --git a/http.c b/http.c index 1865f80..82d9691 100644 --- a/http.c +++ b/http.c @@ -29,6 +29,7 @@ #include "util.h" #include "misc.h" #include "storage.h" +#include "geohash.h" #include "udata.h" #ifdef HAVE_HTTP # include "http.h" @@ -226,11 +227,15 @@ static int json_response(struct mg_connection *conn, JsonNode *json) mg_send_header(conn, "Content-Type", "application/json"); mg_send_header(conn, "Access-Control-Allow-Origin", "*"); - if ((js = json_stringify(json, JSON_INDENT)) != NULL) { - mg_printf_data(conn, js); - free(js); + if (json == NULL) { + mg_printf_data(conn, "{}"); + } else { + if ((js = json_stringify(json, JSON_INDENT)) != NULL) { + mg_printf_data(conn, js); + free(js); + } + json_delete(json); } - json_delete(json); return (MG_TRUE); } @@ -257,7 +262,7 @@ static int dispatch(struct mg_connection *conn, const char *uri) char *time_from = NULL, *time_to = NULL; time_t s_lo, s_hi; JsonNode *json, *obj, *locs; - // struct udata *ud = (struct udata *)conn->server_param; + struct udata *ud = (struct udata *)conn->server_param; if ((nparts = splitter((char *)uri, "/", uparts)) == -1) { @@ -392,6 +397,25 @@ static int dispatch(struct mg_connection *conn, const char *uri) } } + if (nparts == 1 && !strcmp(uparts[0], "q")) { + JsonNode *geo = NULL; + char *lat = field(conn, "lat"); + char *lon = field(conn, "lon"); + char *ghash; + + if (lat && lon) { + if ((ghash = geohash_encode(atof(lat), atof(lon), geohash_prec())) != NULL) { + geo = gcache_json_get(ud->gc, ghash); + free(ghash); + } + } + + if (lat) free(lat); + if (lon) free(lon); + + return (json_response(conn, geo)); + } + // mg_printf_data(conn, "user=[%s], device=[%s]\n", (u) ? u : "", (d) ? d : ""); mg_printf_data(conn, "no comprendo");