I found this nice tutorial on retrieving data about recent earthquakes (from US gov service) - it nicely prints the place and magniuted of every event! Thanks to Christopher (@cskonopka )!
Example uses Go
- and I'm currently studying this language. It seems, however, that for simple JSON retrieval/parsing task compiled languages are not excellent. I'm from Java
world myself and it is always weird for me to create special class or structure repeating the expected JSON.
I feel Python
or PHP
may give easier code. So let's try for comparison (I choose PHP
as it's syntactically closer to Go
). I promise to find did struct-less approach in Go too :)
Let's code!
Firstly - create url by glueing the service address and date parameters:
$url = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson";
$today = date('Y-m-d');
$yesterday = date('Y-m-d', time() - 24 * 60 * 60);
$fullUrl = "$url&starttime=$yesterday&endtime=$today";
Second step - fetch data, check for error and parse json:
$data = file_get_contents($fullUrl);
if ($data === false) {
echo "Error retrieving json\n";
exit(1);
}
$json = json_decode($data);
Third and last - let's print places and magnitudes of events!
foreach ($json->features as $record) {
$prop = $record->properties;
echo "{$prop->place} {$prop->mag}\n";
}
Analysis
So the code has much similarity between PHP and Go, but we get some leisure due to:
- ready functions to perform HTTP request and parse JSON
- fact that scripting language creates structs from JSON "on the fly"
The last is quite nice feature to me, as I mentioned, working in backend services with Java and similar compiled languages, I always felt it is painful rewriting and rebuilding files in several projects when some JSON response format is changed (this is especially true if some strictly-thinking colleague makes unmarshaller break upon new/unknown attributes).
However, as I said, I'm going now to try and see for struct-less approach in Go (brief googling hints there are ways). Hope to post this separately when I build example.
Thanks for reading that far :)
Top comments (6)
You could simplify the way you get yesterday fairly easily with the following:
You could also use:
Wow, thanks :) You see, though I'm not professional PHP dev and thus I don't know many such nice "short-cuts"... Thanks a lot!
PHP has a very nice way to handle dates you can do things like:
That made my day! They probably spent significant efforts on parsing this :) On the other hand it is easier to use than whimsical functions and constants in go "time" package. Thank you once more!
You can do it with Go. See more details:
medium.com/@irshadhasmat/golang-si...
Yep, thanks! I've written code today, but haven't yet created the post I promised :)