Created
January 31, 2018 12:14
-
-
Save codingconcepts/1e3d139f911c402d90f6cc5f55288839 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"encoding/binary" | |
"fmt" | |
"time" | |
) | |
const ( | |
randLen = 4 | |
) | |
func main() { | |
for i := 0; i < 10; i++ { | |
id, _ := newID("UK") | |
fmt.Println(id) | |
} | |
} | |
type id struct { | |
country string | |
timestsamp uint32 | |
random []byte | |
} | |
func newID(country string) (i id, err error) { | |
r, err := random(randLen) | |
if err != nil { | |
return | |
} | |
return id{ | |
country: country, | |
timestsamp: uint32(time.Now().UTC().Unix()), | |
random: r, | |
}, nil | |
} | |
func (i id) String() string { | |
bytes := make([]byte, 4+randLen) | |
binary.BigEndian.PutUint32(bytes, i.timestsamp) | |
copy(bytes[4:], i.random) | |
return fmt.Sprintf("%s-%x-%x", i.country, bytes[:4], bytes[4:]) | |
} | |
func random(l int) (b []byte, err error) { | |
b = make([]byte, l) | |
_, err = rand.Read(b) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment