Skip to content

Instantly share code, notes, and snippets.

@codingconcepts
Created January 31, 2018 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingconcepts/1e3d139f911c402d90f6cc5f55288839 to your computer and use it in GitHub Desktop.
Save codingconcepts/1e3d139f911c402d90f6cc5f55288839 to your computer and use it in GitHub Desktop.
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