本文整理汇总了Golang中net/textproto.MIMEHeader函数的典型用法代码示例。如果您正苦于以下问题:Golang MIMEHeader函数的具体用法?Golang MIMEHeader怎么用?Golang MIMEHeader使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MIMEHeader函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestGetObject
func TestGetObject(t *testing.T) {
header := http.Header{}
textproto.MIMEHeader(header).Add("Content-Type", "image/jpeg")
textproto.MIMEHeader(header).Add("Content-ID", "123456")
textproto.MIMEHeader(header).Add("Object-ID", "1")
textproto.MIMEHeader(header).Add("Preferred", "1")
textproto.MIMEHeader(header).Add("UID", "1a234234234")
textproto.MIMEHeader(header).Add("Content-Description", "Outhouse")
textproto.MIMEHeader(header).Add("Content-Sub-Description", "The urinal")
textproto.MIMEHeader(header).Add("Location", "http://www.simpleboundary.com/image-5.jpg")
var body string = `<binary data 1>`
reader := ioutil.NopCloser(bytes.NewReader([]byte(body)))
quit := make(chan struct{})
defer close(quit)
results := parseGetObjectResult(quit, header, reader)
result := <-results
o := result.Object
testutils.Ok(t, result.Err)
testutils.Equals(t, true, o.Preferred)
testutils.Equals(t, "image/jpeg", o.ContentType)
testutils.Equals(t, "123456", o.ContentId)
testutils.Equals(t, 1, o.ObjectId)
testutils.Equals(t, "1a234234234", o.Uid)
testutils.Equals(t, "Outhouse", o.Description)
testutils.Equals(t, "The urinal", o.SubDescription)
testutils.Equals(t, "<binary data 1>", string(o.Blob))
testutils.Equals(t, "http://www.simpleboundary.com/image-5.jpg", o.Location)
testutils.Equals(t, false, o.RetsError)
}
示例2: AddText
func (p *Multipart) AddText(mediaType string, txt string) error {
if p.isClosed {
return ErrPartClosed
}
p.header = textproto.MIMEHeader(map[string][]string{
"Content-Type": {mediaType},
"Content-Transfer-Encoding": {"quoted-printable"},
})
w, err := p.writer.CreatePart(p.header)
if err != nil {
return err
}
encoder := qp.NewWriter(w)
_, err = io.WriteString(encoder, txt)
if err != nil {
return err
}
encoder.Close()
fmt.Fprintf(w, crlf)
fmt.Fprintf(w, crlf)
return nil
}
示例3: AddText
// AddText applies quoted-printable encoding to the content of r before writing
// the encoded result in a new sub-part with media MIME type set to mediaType.
//
// Specifying the charset in the mediaType string is recommended
// ("plain/text; charset=utf-8").
func (p *Multipart) AddText(mediaType string, r io.Reader) error {
if p.isClosed {
return ErrPartClosed
}
p.header = textproto.MIMEHeader(map[string][]string{
"Content-Type": {mediaType},
"Content-Transfer-Encoding": {"quoted-printable"},
})
w, err := p.writer.CreatePart(p.header)
if err != nil {
return err
}
reader := bufio.NewReader(r)
encoder := qp.NewWriter(w)
defer encoder.Close()
buffer := make([]byte, maxLineLen)
for {
read, err := reader.Read(buffer[:])
if err != nil {
if err != io.EOF {
return err
}
break
}
encoder.Write(buffer[:read])
}
fmt.Fprintf(w, crlf)
fmt.Fprintf(w, crlf)
return nil
}
示例4: getHeader
func getHeader(i map[string][]string, header string) string {
h, ok := textproto.MIMEHeader(i)[textproto.CanonicalMIMEHeaderKey(header)]
if ok {
return h[0]
}
return ""
}
示例5: ForEach
// ForEach ...
func (r *GetObjectResponse) ForEach(result GetObjectResult) error {
resp := r.response
defer resp.Body.Close()
mediaType, params, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return err
}
// its not multipart, just leave
if !strings.HasPrefix(mediaType, "multipart/") {
return result(NewObjectFromStream(textproto.MIMEHeader(resp.Header), resp.Body))
}
// its multipart, need to break it up
partsReader := multipart.NewReader(resp.Body, params["boundary"])
for {
part, err := partsReader.NextPart()
switch {
case err == io.EOF:
return nil
case err != nil:
return err
}
err = result(NewObjectFromStream(part.Header, part))
if err != nil {
return err
}
}
// return nil
}
示例6: getOneRequestFile
// getOneRequestFile reads the first file from the request (if multipart/),
// or returns the body if not
func getOneRequestFile(r *http.Request) (reqFile, error) {
f := reqFile{ReadCloser: r.Body}
contentType := r.Header.Get("Content-Type")
logger.Info("msg", "readRequestOneFile", "ct", contentType)
if !strings.HasPrefix(contentType, "multipart/") {
f.FileHeader.Header = textproto.MIMEHeader(r.Header)
return f, nil
}
defer r.Body.Close()
if err := r.ParseMultipartForm(1 << 20); err != nil {
return f, errors.New("error parsing request as multipart-form: " + err.Error())
}
if r.MultipartForm == nil || len(r.MultipartForm.File) == 0 {
return f, errors.New("no files?")
}
for _, fileHeaders := range r.MultipartForm.File {
for _, fileHeader := range fileHeaders {
var err error
if f.ReadCloser, err = fileHeader.Open(); err != nil {
return f, fmt.Errorf("error opening part %q: %s", fileHeader.Filename, err)
}
f.FileHeader = *fileHeader
return f, nil
}
}
return reqFile{}, nil
}
示例7: mkArticle
func (cb *couchBackend) mkArticle(ar Article) *nntp.Article {
url := fmt.Sprintf("%s/%s/article", cb.db.DBURL(), cleanupId(ar.MsgId, true))
return &nntp.Article{
Header: textproto.MIMEHeader(ar.Headers),
Body: &lazyOpener{url, nil, nil},
Bytes: ar.Bytes,
Lines: ar.Lines,
}
}
示例8: Text
// Text sets the text content of the email.
func (e *Email) Text(text string) {
if nil == e.alternative {
panic("e.alternative IS NIL")
}
out, _ := e.alternative.CreatePart(textproto.MIMEHeader(map[string][]string{
"Content-Type": []string{"text/plain; charset=utf-8"},
}))
fmt.Fprintln(out, text)
}
示例9: AddAttachment
// AddAttachment encodes the content of r in base64 and writes it as an
// attachment of type attachType in this part.
//
// filename is the file name that will be suggested by the mail user agent to a
// user who would like to download the attachment. It's also the value to which
// the Content-ID header will be set. A name with an extension such as
// "report.docx" or "photo.jpg" is recommended. RFC 5987 is not supported, so
// the charset is restricted to ASCII characters.
//
// mediaType indicates the content type of the attachment. If an empty string is
// passed, mime.TypeByExtension will first be called to deduce a value from the
// extension of filemame before defaulting to "application/octet-stream".
//
// In the following example, the media MIME type will be set to "image/png"
// based on the ".png" extension of the filename "gopher.png":
// part.AddAttachment(Inline, "gopher.png", "", image)
func (p *Multipart) AddAttachment(attachType AttachmentType, filename, mediaType string, r io.Reader) (err error) {
if p.isClosed {
return ErrPartClosed
}
// Default Content-Type value
if mediaType == "" && filename != "" {
mediaType = mime.TypeByExtension(filepath.Ext(filename))
}
if mediaType == "" {
mediaType = "application/octet-stream"
}
header := textproto.MIMEHeader(map[string][]string{
"Content-Type": {mediaType},
"Content-ID": {fmt.Sprintf("<%s>", filename)},
"Content-Location": {fmt.Sprintf("%s", filename)},
"Content-Transfer-Encoding": {"base64"},
"Content-Disposition": {fmt.Sprintf("%s;\r\n\tfilename=%s;", attachType, filename)},
})
w, err := p.writer.CreatePart(header)
if err != nil {
return err
}
encoder := base64.NewEncoder(base64.StdEncoding, w)
data := bufio.NewReader(r)
buffer := make([]byte, int(math.Ceil(maxLineLen/4)*3))
for {
read, err := io.ReadAtLeast(data, buffer[:], len(buffer))
if err != nil {
if err == io.EOF {
break
} else if err != io.ErrUnexpectedEOF {
return err
}
}
if _, err := encoder.Write(buffer[:read]); err != nil {
return err
}
if read == len(buffer) {
fmt.Fprintf(w, crlf)
}
}
encoder.Close()
fmt.Fprintf(w, crlf)
return nil
}
示例10: GetHeader
// GetHeader returns the undecoded value of header if found. To access the
// raw (potentially encoded) value of header, use the Message.Header.
func (m *Message) GetHeader(header string) string {
e := textproto.MIMEHeader(m.Header).Get(header)
if e == "" {
return ""
}
dec := new(qp.WordDecoder)
decoded, err := dec.DecodeHeader(e)
if err != nil {
return ""
}
return decoded
}
示例11: parseGetObjectResult
func parseGetObjectResult(quit <-chan struct{}, header http.Header, body io.ReadCloser) <-chan GetObjectResult {
data := make(chan GetObjectResult)
go func() {
defer body.Close()
defer close(data)
select {
case data <- parseHeadersAndStream(textproto.MIMEHeader(header), body):
case <-quit:
return
}
}()
return data
}
示例12: GetMultipleHeaderValues
func (m *Message) GetMultipleHeaderValues(header string) (values []string) {
headers := textproto.MIMEHeader(m.Header)
list := headers[header]
for _, v := range list {
dec := new(qp.WordDecoder)
decoded, err := dec.DecodeHeader(v)
if err != nil {
continue
}
values = append(values, decoded)
}
return values
}
示例13: newResponseParameters
func newResponseParameters(shared bool, cacheRequest *cacheRequest, resource *Resource) (int, int64, http.Header, io.ReadCloser, error) {
age, err := resource.Age()
if err != nil {
return int(http.StatusInternalServerError), -1, nil, nil, err
}
contentLength := resource.ContentLength()
statusCode := resource.Status()
headers := make(http.Header)
for key, mimeheaders := range resource.Header() {
for _, header := range mimeheaders {
textproto.MIMEHeader(headers).Add(key, header)
}
}
// http://httpwg.github.io/specs/rfc7234.html#warn.113
if age > (time.Hour*24) && resource.HeuristicFreshness() > (time.Hour*24) {
textproto.MIMEHeader(headers).Add("Warning", `113 - "Heuristic Expiration"`)
}
// http://httpwg.github.io/specs/rfc7234.html#warn.110
freshness, err := freshness(shared, resource, cacheRequest)
if err != nil || freshness <= 0 {
textproto.MIMEHeader(headers).Add("Warning", `110 - "Response is Stale"`)
}
debugf("resource is %s old, updating age from %s", age.String(), headers.Get("Age"))
textproto.MIMEHeader(headers).Set("Age", fmt.Sprintf("%.f", math.Floor(age.Seconds())))
textproto.MIMEHeader(headers).Set("Via", resource.Via())
body := resource
return statusCode, contentLength, headers, body, nil
}
示例14: Walk
// Walk over the parts of the email, calling todo on every part.
// The part.Body given to todo is reused, so read if you want to use it!
//
// By default this is recursive, except dontDescend is true.
func Walk(part MailPart, todo TodoFunc, dontDescend bool) error {
br, e := temp.NewReadSeeker(part.Body)
if e != nil {
return e
}
defer func() { _ = br.Close() }()
msg, hsh, e := ReadAndHashMessage(br)
if e != nil {
return errgo.Notef(e, "WalkMail")
}
ct, params, decoder, e := getCT(msg.Header)
logger.Info("msg", "Walk message", "hsh", hsh, "headers", msg.Header)
if e != nil {
return errgo.Notef(e, "WalkMail")
}
if ct == "" {
ct = "message/rfc822"
}
child := MailPart{ContentType: ct, MediaType: params,
Header: textproto.MIMEHeader(msg.Header),
Body: msg.Body, Parent: &part,
Level: part.Level + 1,
Seq: nextSeqInt()}
child.Header.Add("X-Hash", hsh)
if child.Header.Get(HashKeyName) == "" {
child.Header.Add(HashKeyName, hsh)
}
logger.Debug("msg", "message", "sequence", child.Seq, "content-type", ct, "params", params)
if strings.HasPrefix(ct, "multipart/") {
return WalkMultipart(child, todo, dontDescend)
}
if !dontDescend && strings.HasPrefix(ct, "message/") { //mail
if decoder != nil {
child.Body = decoder(child.Body)
}
if e = Walk(child, todo, dontDescend); e != nil {
return errgo.Notef(e, "WalkMail descending")
}
return nil
}
//simple
if decoder != nil {
child.Body = decoder(child.Body)
}
if e = todo(child); e != nil {
return errgo.Notef(e, "todo")
}
return nil
}
示例15: TestGetObject
func TestGetObject(t *testing.T) {
header := http.Header{}
textproto.MIMEHeader(header).Add("Content-Type", "image/jpeg")
textproto.MIMEHeader(header).Add("Content-ID", "123456")
textproto.MIMEHeader(header).Add("Object-ID", "1")
textproto.MIMEHeader(header).Add("Preferred", "1")
textproto.MIMEHeader(header).Add("UID", "1a234234234")
textproto.MIMEHeader(header).Add("Content-Description", "Outhouse")
textproto.MIMEHeader(header).Add("Content-Sub-Description", "The urinal")
textproto.MIMEHeader(header).Add("Location", "http://www.simpleboundary.com/image-5.jpg")
var body = `<binary data 1>`
response := GetObjectResponse{
response: &http.Response{
Header: header,
Body: ioutil.NopCloser(strings.NewReader(body)),
},
}
defer response.Close()
var objects []*Object
err := response.ForEach(func(o *Object, err error) error {
objects = append(objects, o)
return nil
})
testutils.Ok(t, err)
testutils.Equals(t, 1, len(objects))
o := objects[0]
testutils.Equals(t, true, o.Preferred)
testutils.Equals(t, "image/jpeg", o.ContentType)
testutils.Equals(t, "123456", o.ContentID)
testutils.Equals(t, 1, o.ObjectID)
testutils.Equals(t, "1a234234234", o.UID)
testutils.Equals(t, "Outhouse", o.Description)
testutils.Equals(t, "The urinal", o.SubDescription)
testutils.Equals(t, "<binary data 1>", string(o.Blob))
testutils.Equals(t, "http://www.simpleboundary.com/image-5.jpg", o.Location)
testutils.Equals(t, false, o.RetsError)
}