go - 如何在 golang 中生成一组确定性的 UUID
问题描述
我正在做一些测试,如果我们的代码使用一组已知的 UUID,这将很有用。但是,我无法弄清楚如何在 golang 中创建一组确定性的 UUID。
我尝试了几种方法,但似乎都不起作用:
type KnownReader struct {
store *Store
}
type Store struct {
val uint16
}
func (r KnownReader) Read(p []byte) (n int, err error) {
ret := r.store.val
r.store.val = ret + 1
fmt.Printf("\nStore: %v", r.store.val)
p = make([]byte, 4)
binary.LittleEndian.PutUint16(p, uint16(ret))
fmt.Printf("\nreader p: % x", p)
return binary.MaxVarintLen16, nil
}
func main() {
r := KnownReader{
store: &Store{val: 111},
}
uuid.SetRand(r)
u, _ := uuid.NewRandomFromReader(r)
fmt.Printf("\n%v",u)
u, _ = uuid.NewRandomFromReader(r)
fmt.Printf("\n%v",u)
}
---- OUTPUT ----
Store: 1
reader p: 00 00 00 00
Store: 2
reader p: 01 00 00 00
Store: 3
reader p: 02 00 00 00
Store: 4
reader p: 03 00 00 00
Store: 5
reader p: 04 00 00 00
Store: 6
reader p: 05 00 00 00
00000000-0000-4000-8000-000000000000
Store: 7
reader p: 06 00 00 00
Store: 8
reader p: 07 00 00 00
Store: 9
reader p: 08 00 00 00
Store: 10
reader p: 09 00 00 00
Store: 11
reader p: 0a 00 00 00
Store: 12
reader p: 0b 00 00 00
00000000-0000-4000-8000-000000000000
如您所见,UUID 在调用之间不会改变
我也尝试使用 uuid.FromBytes,但这似乎也不起作用:
func getbytes(num uint16) []byte {
p := make([]byte, 4)
binary.LittleEndian.PutUint16(p, num)
fmt.Printf("\ngetbytes p: % x", p)
return p
}
func main() {
var i uint16 = 0
fmt.Printf("\nout getbytes: % x", getbytes(i))
u, _ := uuid.FromBytes(getbytes(i))
i = i + 1
fmt.Printf("\nUUID: %v", u)
fmt.Printf("\nout getbytes: % x", getbytes(i))
u, _ = uuid.FromBytes(getbytes(i))
fmt.Printf("\nUUID: %v", u)
}
---- OUTPUT ----
getbytes p: 00 00 00 00
out getbytes: 00 00 00 00
getbytes p: 00 00 00 00
UUID: 00000000-0000-0000-0000-000000000000
getbytes p: 01 00 00 00
out getbytes: 01 00 00 00
getbytes p: 01 00 00 00
UUID: 00000000-0000-0000-0000-000000000000
如您所见,这里的 UUID 仍然相同。
那么,有什么我想念的吗?如何获得一组一致的 UUID?
谢谢
解决方案
谢谢阿德里安,我想我找到了答案:
rnd := rand.New(rand.NewSource(1))
uuid.SetRand(rnd)
u, _ = uuid.NewRandomFromReader(rnd)
fmt.Printf("\n%v", u)
u, _ = uuid.NewRandomFromReader(rnd)
fmt.Printf("\n%v", u)
--- OUTPUT ---
52fdfc07-2182-454f-963f-5f0f9a621d72
9566c74d-1003-4c4d-bbbb-0407d1e2c649
推荐阅读
- python - 有没有办法查看张量板图中的参数总数?
- css - 为什么我的图像使用旋转后会出现垂直滚动条?
- python - Elasticsearch 和 S3 存储桶:如何让 Python 检测来自 s3 存储桶的数据是否已经在弹性搜索中?
- ruby-on-rails - React::ServerRendering::PrerenderError - Rails 5,React 预渲染问题
- http - 向 grpc-gateway 服务器发出请求时出现 HTTP2 PROTOCOL_ERROR
- ruby - Logstash Ruby 无效的转义字符语法
- bash - Shell 脚本在 crontab 中无法正常运行
- android - 如何与我的图书馆共享 NewRelic 实例
- angular - 需要相同库的两个项目
- python - 模块(文本提取 PDF 提取器)在控制台与 PyCharm 中运行时提供不同的输出