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 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流