英文:
Repeatedly storing JSON logs as files with Go and ensuring unique filenames
问题
作为一个新手,我正在使用Go语言,并且我从一个API中重复地接收到一个很小(约1KB)的JSON文件,它实际上是一个日志文件,我想保留每一个这样的文件。
我考虑的是将每个JSON块存储为一个唯一的文件(而不是使用数据库,这似乎是不必要的),并将它们存储在一个特定的目录中。
首先,这个想法可行吗?每天可能会有几百个文件。
更重要的是,如何确保文件名的唯一性?显然,我不能只是将每个文件保存为log.json
,因为会产生冲突。我该如何确保唯一性?
英文:
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?
答案1
得分: 2
无论是不是一个好主意,都可以使用ioutil.TempFile
来确保你拥有唯一的文件名。TempFile
会在你选择的文件前缀后附加一个保证唯一的后缀。
f, err := ioutil.TempFile(storeDirectory, fileName)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论