Doug Smith Doug Smith - 28 days ago 6
JSON Question

Repeatedly storing JSON logs as files with Go and ensuring unique filenames

A bit of a newcomer to Go, and I'm effectively receiving a small (~1KB) JSON file from an API repeatedly that is effectively a log, and I want to keep each one of these files.

I'm thinking just storing each JSON block as a unique file (in lieu of using a database, which seems unnecessary) in a specific directory.

First off, is this an okay idea? There could be potentially a few hundred per day.

More importantly, how do I ensure uniqueness across filenames? Obviously I can't just save each one as

log.json
and call it a day, as there would be conflicts. How would I ensure uniqueness?

Answer

Whether it's agood idea or not is subjective, but you can use ioutil.TempFile to ensure you have unique filenames. TempFile will append a guaranteed unique suffix to the file prefix you choose.

f, err := ioutil.TempFile(storeDirectory, fileName)
Comments