Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
56 lines (42 sloc) 1.6 KB
/*
Title: 55.Base64_Encoding.go
Author: OpenSource
Date: 2017-05-23
Description: For Study
Go provides built-in support for base64 encoding/decoding.
*/
package main
// This syntax imports the encoding/base64 package with the b64 name
// instead of the default base64. It’ll save us some space below.
import b64 "encoding/base64"
import "fmt"
func main(){
fmt.Println("55.Base64_Encoding.go---------Start------------\n\n")
// Here's the string we'll encode/decode.
data := "abc123!?$*&()'-=@~"
// Go supports both standard and URL-compatible base64.
// Here’s how to encode using the standard encoder.
// The encoder requires a []byte so we cast our string to that type.
sEnc := b64.StdEncoding.EncodeToString([]byte(data))
fmt.Println(data)
fmt.Println(sEnc)
fmt.Println()
// Decoding may return an error,
// which you can check if you don’t already know the input to be well-formed.
sDec, _ := b64.StdEncoding.DecodeString(sEnc)
fmt.Println(sEnc)
fmt.Println(sDec)
fmt.Println(string(sDec))
fmt.Println()
// This encodes/decodes using a URL-compatible base64 format.
uEnc := b64.URLEncoding.EncodeToString([]byte(data))
fmt.Println(uEnc)
uDec, _ := b64.URLEncoding.DecodeString(uEnc)
fmt.Println(uDec)
fmt.Println(string(uDec))
fmt.Println()
fmt.Println("\n\n55.Base64_Encoding.go---------Ending------------\n\n")
// The string encodes to slightly different values
// with the standard and URL base64 encoders (trailing + vs -)
// but they both decode to the original string as desired.
}
You can’t perform that action at this time.