github.com/la5nta/wl2k-go@v0.11.8/fbb/message_body.go (about) 1 // Copyright 2015 Martin Hebnes Pedersen (LA5NTA). All rights reserved. 2 // Use of this source code is governed by the MIT-license that can be 3 // found in the LICENSE file. 4 5 package fbb 6 7 import ( 8 "bufio" 9 "bytes" 10 11 "github.com/paulrosania/go-charset/charset" 12 _ "github.com/paulrosania/go-charset/data" 13 ) 14 15 // StringToBytes converts the body into a slice of bytes with the given charset encoding. 16 // 17 // CRLF line break is enforced. 18 // Line break are inserted if a line is longer than 1000 characters (including CRLF). 19 func StringToBody(str, encoding string) ([]byte, error) { 20 in := bufio.NewScanner(bytes.NewBufferString(str)) 21 out := new(bytes.Buffer) 22 23 var err error 24 var line []byte 25 for in.Scan() { 26 line = in.Bytes() 27 for { 28 // Lines can not be longer that 1000 characters including CRLF. 29 n := min(len(line), 1000-2) 30 31 out.Write(line[:n]) 32 out.WriteString("\r\n") 33 34 line = line[n:] 35 if len(line) == 0 { 36 break 37 } 38 } 39 } 40 41 translator, err := charset.TranslatorTo(encoding) 42 if err != nil { 43 return out.Bytes(), err 44 } 45 46 _, translated, err := translator.Translate(out.Bytes(), true) 47 return translated, err 48 } 49 50 func min(a, b int) int { 51 if a < b { 52 return a 53 } 54 return b 55 } 56 57 // BodyFromBytes translated the data based on the given charset encoding into a proper utf-8 string. 58 func BodyFromBytes(data []byte, encoding string) (string, error) { 59 translator, err := charset.TranslatorFrom(encoding) 60 if err != nil { 61 return string(data), err 62 } 63 64 _, utf8, err := translator.Translate(data, true) 65 return string(utf8), err 66 }