From 3f9e18e948077ec8aa686f31d1014aea27640e19 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan <mmcgrana@gmail.com> Date: Wed, 24 Oct 2012 10:03:48 -0400 Subject: [PATCH] publish base64-encoding --- examples.txt | 2 +- examples/base64-encoding/base64-encoding.go | 25 ++++++++++++++++----- examples/base64-encoding/base64-encoding.sh | 9 ++++++++ 3 files changed, 29 insertions(+), 7 deletions(-) create mode 100644 examples/base64-encoding/base64-encoding.sh diff --git a/examples.txt b/examples.txt index 8a0f8cc..32f7513 100644 --- a/examples.txt +++ b/examples.txt @@ -56,7 +56,7 @@ Defer # Number Parsing # URLs SHA1 Hashes -# Base64 Encoding +Base64 Encoding # Reading Files # Writing Files Line Filters diff --git a/examples/base64-encoding/base64-encoding.go b/examples/base64-encoding/base64-encoding.go index e27a592..d37167f 100644 --- a/examples/base64-encoding/base64-encoding.go +++ b/examples/base64-encoding/base64-encoding.go @@ -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) diff --git a/examples/base64-encoding/base64-encoding.sh b/examples/base64-encoding/base64-encoding.sh new file mode 100644 index 0000000..a1980f2 --- /dev/null +++ b/examples/base64-encoding/base64-encoding.sh @@ -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!?$*&()'-=@~