publish base64-encoding
This commit is contained in:
parent
76804c3097
commit
3f9e18e948
@ -56,7 +56,7 @@ Defer
|
||||
# Number Parsing
|
||||
# URLs
|
||||
SHA1 Hashes
|
||||
# Base64 Encoding
|
||||
Base64 Encoding
|
||||
# Reading Files
|
||||
# Writing Files
|
||||
Line Filters
|
||||
|
@ -1,22 +1,35 @@
|
||||
// Go provides built-in support for [base64
|
||||
// encoding/decoding](http://en.wikipedia.org/wiki/Base64).
|
||||
|
||||
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() {
|
||||
// The data we'll encode/decode.
|
||||
data := "abc123!?$*&()'-=@~"
|
||||
fmt.Println(data)
|
||||
fmt.Println()
|
||||
|
||||
// Standard base64 encoding/decoding.
|
||||
// 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(sEnc)
|
||||
|
||||
// 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(string(sDec))
|
||||
fmt.Println()
|
||||
|
||||
// URL base64 encoding/decoding.
|
||||
// This encodes/decodes using a URL-compatible base64
|
||||
// format.
|
||||
uEnc := b64.URLEncoding.EncodeToString([]byte(data))
|
||||
fmt.Println(uEnc)
|
||||
uDec, _ := b64.URLEncoding.DecodeString(uEnc)
|
||||
|
9
examples/base64-encoding/base64-encoding.sh
Normal file
9
examples/base64-encoding/base64-encoding.sh
Normal file
@ -0,0 +1,9 @@
|
||||
# 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.
|
||||
$ go run base64-encoding.sh
|
||||
YWJjMTIzIT8kKiYoKSctPUB+
|
||||
abc123!?$*&()'-=@~
|
||||
|
||||
YWJjMTIzIT8kKiYoKSctPUB-
|
||||
abc123!?$*&()'-=@~
|
Loading…
x
Reference in New Issue
Block a user