英文:
Base64 encoded uuid is longer than expected
问题
对于我的 RESTful API,我想基于 URL 安全的 base42 编码 UUID 版本 4 来实现较短的 URL(将来我将使用 MongoDB 的内部 UUID)。生成工作正常,但是 Go 的 base64 库似乎没有按预期将 UUID 编码为字符串。输出长度为 48 个字符,而不是 22 个字符(如 Python 中所示)。
以下是我的代码:
package main
import (
"encoding/base64"
"fmt"
"github.com/nu7hatch/gouuid"
)
func printRandomUUID() {
uid, _ := uuid.NewV4()
uid64 := base64.URLEncoding.EncodeToString([]byte(uid.String()))
fmt.Println(uid64, len(uid64))
}
func main() {
for i := 0; i < 5; i++ {
printRandomUUID()
}
}
以下是可能的输出:
OGJhNzdhODItNjc5Yi00OWIyLTYwOGEtODZkYjA2Mzk0MDJj 48
YzE3YTNmY2EtOWM1MC00ZjE2LTQ3YTAtZGI3ZGQyNGI4N2Fj 48
ODFmZDU3ZDgtNjA2Ni00ZjYwLTUyMDUtOTU0MDVhYzNjZTNh 48
NjhkNTY3ZDAtOGE1Yy00ZGY2LTVmZmMtZTg2ZDEwOTlmZjU3 48
MzhhZmU0MDctMDE3Ny00YjhjLTYyYzctYWYwMWNlMDkwOWRh 48
如上所示,输出并没有变短,反而变长了!我是不是错误地实现了编码?
英文:
For my restful api I want to implement shorter urls based on url-safe base42-encoded UUID's version 4 (In future I'll use MongoDB's internal one's instead).
The generation works fine, but the base64 library of Go doesn't seem to encode the UUID as string as expected. The outpout is 48 characters long instead of 22 (as shown here in Python).
Here is my code:
package main
import (
"encoding/base64"
"fmt"
"github.com/nu7hatch/gouuid"
)
func printRandomUUID() {
uid, _ := uuid.NewV4()
uid64 := base64.URLEncoding.EncodeToString([]byte(uid.String()))
fmt.Println(uid64, len(uid64))
}
func main() {
for i := 0; i < 5; i++ {
printRandomUUID()
}
}
And here is a possible output:
OGJhNzdhODItNjc5Yi00OWIyLTYwOGEtODZkYjA2Mzk0MDJj 48
YzE3YTNmY2EtOWM1MC00ZjE2LTQ3YTAtZGI3ZGQyNGI4N2Fj 48
ODFmZDU3ZDgtNjA2Ni00ZjYwLTUyMDUtOTU0MDVhYzNjZTNh 48
NjhkNTY3ZDAtOGE1Yy00ZGY2LTVmZmMtZTg2ZDEwOTlmZjU3 48
MzhhZmU0MDctMDE3Ny00YjhjLTYyYzctYWYwMWNlMDkwOWRh 48
<br>
As shown is the output not shorter but longer! Did I implemented the encoding the wrong way?
答案1
得分: 4
你正在对一个编码进行编码。
uid.String()
生成一个十六进制字符串,然后你使用 base64 对这些字符进行编码。
你想要对字节进行编码:
uid64 := base64.URLEncoding.EncodeToString(uid[:])
uid[:]
将 [16]byte
转换为切片,这是 EncodeToString
所需的格式。
在我的机器上,这将产生以下结果:
EaHttz1oSvJnCVQOaPWLAQ== 24
JEqjA6xfQD9-Ebp4Lai0DQ== 24
UWvn3zWYRPdPXcE9bbDX9w== 24
mBMNZB4FSmlRl6t4bDOiHA== 24
O1JTaQHBRm1RP5FLB7pbwQ== 24
英文:
You are encoding an encoding
uid.String()
Produces a hex string, you are then encoding those characters with base64.
you want to encode the bytes instead:
uid64 := base64.URLEncoding.EncodeToString(uid[:])
the uid[:] turns the [16]byte in to a slice, which is what EncodeToString requires.
On my machine, this produces:
EaHttz1oSvJnCVQOaPWLAQ== 24
JEqjA6xfQD9-Ebp4Lai0DQ== 24
UWvn3zWYRPdPXcE9bbDX9w== 24
mBMNZB4FSmlRl6t4bDOiHA== 24
O1JTaQHBRm1RP5FLB7pbwQ== 24
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论