1 Star 0 Fork 0

wpkg / message

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
encoding.go 1.99 KB
一键复制 编辑 原始数据 按行查看 历史
arvin 提交于 2023-01-06 04:17 . sync at Fri 06 Jan 2023 04:17:43 AM CST
package message
import (
"encoding/base64"
"errors"
"fmt"
"io"
"mime/quotedprintable"
"strings"
"gitee.com/wpkg/message/textwrapper"
)
type UnknownEncodingError struct {
e error
}
func (u UnknownEncodingError) Unwrap() error { return u.e }
func (u UnknownEncodingError) Error() string {
return "encoding error: " + u.e.Error()
}
// IsUnknownEncoding returns a boolean indicating whether the error is known to
// report that the encoding advertised by the entity is unknown.
func IsUnknownEncoding(err error) bool {
return errors.As(err, new(UnknownEncodingError))
}
func encodingReader(enc string, r io.Reader) (io.Reader, error) {
var dec io.Reader
switch strings.ToLower(enc) {
case "quoted-printable":
dec = quotedprintable.NewReader(r)
case "base64":
wrapped := &whitespaceReplacingReader{wrapped: r}
dec = base64.NewDecoder(base64.StdEncoding, wrapped)
case "7bit", "8bit", "binary", "":
dec = r
default:
return nil, fmt.Errorf("unhandled encoding %q", enc)
}
return dec, nil
}
type nopCloser struct {
io.Writer
}
func (nopCloser) Close() error {
return nil
}
func encodingWriter(enc string, w io.Writer) (io.WriteCloser, error) {
var wc io.WriteCloser
switch strings.ToLower(enc) {
case "quoted-printable":
wc = quotedprintable.NewWriter(w)
case "base64":
wc = base64.NewEncoder(base64.StdEncoding, textwrapper.NewRFC822(w))
case "7bit", "8bit":
wc = nopCloser{textwrapper.New(w, "\r\n", 1000)}
case "binary", "":
wc = nopCloser{w}
default:
return nil, fmt.Errorf("unhandled encoding %q", enc)
}
return wc, nil
}
// whitespaceReplacingReader replaces space and tab characters with a LF so
// base64 bodies with a continuation indent can be decoded by the base64 decoder
// even though it is against the spec.
type whitespaceReplacingReader struct {
wrapped io.Reader
}
func (r *whitespaceReplacingReader) Read(p []byte) (int, error) {
n, err := r.wrapped.Read(p)
for i := 0; i < n; i++ {
if p[i] == ' ' || p[i] == '\t' {
p[i] = '\n'
}
}
return n, err
}
Go
1
https://gitee.com/wpkg/message.git
git@gitee.com:wpkg/message.git
wpkg
message
message
c54e73f07ebd

搜索帮助