github.com/peggyl/go@v0.0.0-20151008231540-ae315999c2d5/src/mime/example_test.go (about) 1 // Copyright 2015 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 package mime_test 6 7 import ( 8 "bytes" 9 "fmt" 10 "io" 11 "io/ioutil" 12 "mime" 13 ) 14 15 func ExampleWordEncoder_Encode() { 16 fmt.Println(mime.QEncoding.Encode("utf-8", "¡Hola, señor!")) 17 fmt.Println(mime.QEncoding.Encode("utf-8", "Hello!")) 18 fmt.Println(mime.BEncoding.Encode("UTF-8", "¡Hola, señor!")) 19 fmt.Println(mime.QEncoding.Encode("ISO-8859-1", "Caf\xE9")) 20 // Output: 21 // =?utf-8?q?=C2=A1Hola,_se=C3=B1or!?= 22 // Hello! 23 // =?UTF-8?b?wqFIb2xhLCBzZcOxb3Ih?= 24 // =?ISO-8859-1?q?Caf=E9?= 25 } 26 27 func ExampleWordDecoder_Decode() { 28 dec := new(mime.WordDecoder) 29 header, err := dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=") 30 if err != nil { 31 panic(err) 32 } 33 fmt.Println(header) 34 35 dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { 36 switch charset { 37 case "x-case": 38 // Fake character set for example. 39 // Real use would integrate with packages such 40 // as code.google.com/p/go-charset 41 content, err := ioutil.ReadAll(input) 42 if err != nil { 43 return nil, err 44 } 45 return bytes.NewReader(bytes.ToUpper(content)), nil 46 default: 47 return nil, fmt.Errorf("unhandled charset %q", charset) 48 } 49 } 50 header, err = dec.Decode("=?x-case?q?hello!?=") 51 if err != nil { 52 panic(err) 53 } 54 fmt.Println(header) 55 // Output: 56 // ¡Hola, señor! 57 // HELLO! 58 } 59 60 func ExampleWordDecoder_DecodeHeader() { 61 dec := new(mime.WordDecoder) 62 header, err := dec.DecodeHeader("=?utf-8?q?=C3=89ric?= <eric@example.org>, =?utf-8?q?Ana=C3=AFs?= <anais@example.org>") 63 if err != nil { 64 panic(err) 65 } 66 fmt.Println(header) 67 68 header, err = dec.DecodeHeader("=?utf-8?q?=C2=A1Hola,?= =?utf-8?q?_se=C3=B1or!?=") 69 if err != nil { 70 panic(err) 71 } 72 fmt.Println(header) 73 74 dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { 75 switch charset { 76 case "x-case": 77 // Fake character set for example. 78 // Real use would integrate with packages such 79 // as code.google.com/p/go-charset 80 content, err := ioutil.ReadAll(input) 81 if err != nil { 82 return nil, err 83 } 84 return bytes.NewReader(bytes.ToUpper(content)), nil 85 default: 86 return nil, fmt.Errorf("unhandled charset %q", charset) 87 } 88 } 89 header, err = dec.DecodeHeader("=?x-case?q?hello_?= =?x-case?q?world!?=") 90 if err != nil { 91 panic(err) 92 } 93 fmt.Println(header) 94 // Output: 95 // Éric <eric@example.org>, Anaïs <anais@example.org> 96 // ¡Hola, señor! 97 // HELLO WORLD! 98 }