重复使用Go将JSON日志存储为文件,并确保文件名唯一。

huangapple go评论74阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2016年11月4日 22:13:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/40424864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定