Created
March 27, 2019 04:15
-
-
Save kilfu0701/269106a43342bc592dc00dbd5ffafefc to your computer and use it in GitHub Desktop.
golang mongodb ObjectID base64 encode & decode. https://play.golang.org/p/IACE8_AE-CT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/base64" | |
"encoding/hex" | |
"fmt" | |
"strings" | |
) | |
func Hex2bin(s string) []byte { | |
ret, err := hex.DecodeString(s) | |
if err != nil { | |
fmt.Printf("%v", err) | |
} | |
return ret | |
} | |
func Bin2Hex(b []byte) string { | |
return hex.EncodeToString(b) | |
} | |
func EncodeIdToBase64(input string) string { | |
s := base64.StdEncoding.EncodeToString(Hex2bin(input)) | |
base64Str := strings.Map(func(r rune) rune { | |
switch r { | |
case '+': | |
return '-' | |
case '/': | |
return '_' | |
} | |
return r | |
}, s) | |
base64Str = strings.ReplaceAll(base64Str, "=", "") | |
return base64Str | |
} | |
func DecodeIdToBase64(input string) string { | |
base64Str := strings.Map(func(r rune) rune { | |
switch r { | |
case '-': | |
return '+' | |
case '_': | |
return '/' | |
} | |
return r | |
}, input) | |
if pad := len(base64Str) % 4; pad > 0 { | |
base64Str += strings.Repeat("=", 4-pad) | |
} | |
b, _ := base64.StdEncoding.DecodeString(base64Str) | |
return Bin2Hex(b) | |
} | |
func main() { | |
// here we use mongodb objectID string | |
str := "5c9adba7d4579ef73cdc6992" | |
e := EncodeIdToBase64(str) | |
fmt.Printf("encoded = %s \n", e) | |
d := DecodeIdToBase64(e) | |
fmt.Printf("decoded = %s \n", d) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment