-
Notifications
You must be signed in to change notification settings - Fork 0
/
base64-encoding.go
39 lines (31 loc) · 1.05 KB
/
base64-encoding.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main
import (
"encoding/base64"
"fmt"
)
// Go provides built-in support for base64 encoding/decoding.
// Go supports both standard and URL-compatible base64.
func main() {
data := "abc123!?$*&()'-=@~"
// The encoder requires a []byte so we cast our string to that type.
bytes := []byte(data)
fmt.Println("Source string:", data)
fmt.Println()
standardEncoding(&bytes)
fmt.Println()
urlEncoding(&bytes)
}
// Here’s how to encode/decode using the standard encoder.
func standardEncoding(bytes *[]byte) {
stdEncoded := base64.StdEncoding.EncodeToString(*bytes)
fmt.Println("Standard encoding:", stdEncoded)
stdDecoded, _ := base64.StdEncoding.DecodeString(stdEncoded)
fmt.Println("Standard decoding:", string(stdDecoded))
}
// Here’s how to encodes/decodes using a URL-compatible base64 format.
func urlEncoding(bytes *[]byte) {
urlEncoded := base64.URLEncoding.EncodeToString(*bytes)
fmt.Println("URL encoding:", urlEncoded)
urlDecoded, _ := base64.URLEncoding.DecodeString(urlEncoded)
fmt.Println("URL decoding:", string(urlDecoded))
}