1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Keep in sync with ../base32/example_test.go. 6 7 package base64_test 8 9 import ( 10 "encoding/base64" 11 "fmt" 12 "os" 13 ) 14 15 func Example() { 16 msg := "Hello, " 17 encoded := base64.StdEncoding.EncodeToString([]byte(msg)) 18 fmt.Println(encoded) 19 decoded, err := base64.StdEncoding.DecodeString(encoded) 20 if err != nil { 21 fmt.Println("decode error:", err) 22 return 23 } 24 fmt.Println(string(decoded)) 25 // Output: 26 // SGVsbG8sIOS4lueVjA== 27 // Hello, 28 } 29 30 func ExampleEncoding_EncodeToString() { 31 data := []byte("any + old & data") 32 str := base64.StdEncoding.EncodeToString(data) 33 fmt.Println(str) 34 // Output: 35 // YW55ICsgb2xkICYgZGF0YQ== 36 } 37 38 func ExampleEncoding_DecodeString() { 39 str := "c29tZSBkYXRhIHdpdGggACBhbmQg77u/" 40 data, err := base64.StdEncoding.DecodeString(str) 41 if err != nil { 42 fmt.Println("error:", err) 43 return 44 } 45 fmt.Printf("%q\n", data) 46 // Output: 47 // "some data with \x00 and \ufeff" 48 } 49 50 func ExampleNewEncoder() { 51 input := []byte("foo\x00bar") 52 encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout) 53 encoder.Write(input) 54 // Must close the encoder when finished to flush any partial blocks. 55 // If you comment out the following line, the last partial block "r" 56 // won't be encoded. 57 encoder.Close() 58 // Output: 59 // Zm9vAGJhcg== 60 } 61