Source file src/encoding/base64/example_test.go

     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_Encode() {
    39  	data := []byte("Hello, world!")
    40  	dst := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
    41  	base64.StdEncoding.Encode(dst, data)
    42  	fmt.Println(string(dst))
    43  	// Output:
    44  	// SGVsbG8sIHdvcmxkIQ==
    45  }
    46  
    47  func ExampleEncoding_DecodeString() {
    48  	str := "c29tZSBkYXRhIHdpdGggACBhbmQg77u/"
    49  	data, err := base64.StdEncoding.DecodeString(str)
    50  	if err != nil {
    51  		fmt.Println("error:", err)
    52  		return
    53  	}
    54  	fmt.Printf("%q\n", data)
    55  	// Output:
    56  	// "some data with \x00 and \ufeff"
    57  }
    58  
    59  func ExampleEncoding_Decode() {
    60  	str := "SGVsbG8sIHdvcmxkIQ=="
    61  	dst := make([]byte, base64.StdEncoding.DecodedLen(len(str)))
    62  	n, err := base64.StdEncoding.Decode(dst, []byte(str))
    63  	if err != nil {
    64  		fmt.Println("decode error:", err)
    65  		return
    66  	}
    67  	dst = dst[:n]
    68  	fmt.Printf("%q\n", dst)
    69  	// Output:
    70  	// "Hello, world!"
    71  }
    72  
    73  func ExampleNewEncoder() {
    74  	input := []byte("foo\x00bar")
    75  	encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
    76  	encoder.Write(input)
    77  	// Must close the encoder when finished to flush any partial blocks.
    78  	// If you comment out the following line, the last partial block "r"
    79  	// won't be encoded.
    80  	encoder.Close()
    81  	// Output:
    82  	// Zm9vAGJhcg==
    83  }
    84  

View as plain text