Goal is to create random path to store files so that I can store large numbers of files with random path.
2 Answers
I'm really not sure why you would want to do this. The capacity of most (all?) systems is so high it's not practical to think about it. If you have to think about it, there's likely another problem. For example, Mac OS X can have 2.1 billion files per folder. Granted, viewing a list of files can be somewhat problematic at some point.
If you want random values, you have the choice of the crypto/rand
and math/rand
packages. The math/rand
package is probably better suited for this situation as crypto/rand
relies on system generated entropy. math/rand
is based on a seeded algorithm. The downside is you'll have to check for collisions. The probability of a collision really depends on how many characters you use. The fewer character you have the more likely the collision will be.
One thing you could do is use a timestamp at some frequency (days, months) for the folder name using the time
package. I would try and avoid random file names as it would make management a nightmare. If there are conflicts, you can always add a suffix to the filename.
I'm assuming, of course, that you'll be storing potentially large binary files, like images. If you're storing something small (text file), you may want to consider using a database.

- 13,678
- 7
- 45
- 79
-
@JVK And...? Code makes no sense to me, other than it has the word "hash" in it. There are other packages like `hash`, `math/rand`, and `time` that you can use. – Luke Aug 07 '13 at 00:00
-
@JVK Your best bet is the #go-nuts freenode IRC channel. – Luke Aug 07 '13 at 04:28
If you want the path to be "random" and not to conflict with any other paths, use SHA-1 to hash the filenames. The odds of a collision are extraordinarily miniscule. If you require the path to be short, just take a substring of the hash, though this obviously increases your chance of path-collision significantly (which may or may not be a problem for you).

- 1
- 1

- 11,471
- 4
- 32
- 47
-
First, it will still have as much 'randomness' as most methods. Second, it sounds like this is a completely artificial use case. Why must you only have two directories? Why must they be two characters long? Most importantly, why go through the pain of having random directories at all? – Chris Hayes Aug 06 '13 at 23:25
-
1100 million files is a ridiculous number for almost any application. It sounds like what you really want is a database. If you insist on this architecture, and on your requirement that the "randomness is calculated on the filename", I don't think you can do better than a hash. – Chris Hayes Aug 06 '13 at 23:31
-
any help you can offer in converting this to go. http://pastebin.com/1562U7w7 – JVK Aug 07 '13 at 04:13