dsi37923 2015-03-31 19:34
浏览 118
已采纳

Base64编码的uuid比预期的长

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


As shown is the output not shorter but longer! Did I implemented the encoding the wrong way?

  • 写回答

1条回答 默认 最新

  • dongzhui2636 2015-03-31 19:52
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)