本文整理汇总了Golang中net/textproto.MIMEHeader类的典型用法代码示例。如果您正苦于以下问题:Golang MIMEHeader类的具体用法?Golang MIMEHeader怎么用?Golang MIMEHeader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MIMEHeader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Date
// Date parses the Date header field.
func Date(h textproto.MIMEHeader) (time.Time, error) {
hdr := h.Get("Date")
if hdr == "" {
return time.Time{}, ErrHeaderNotPresent
}
return parseDate(hdr)
}
示例2: writeJSONPart
func writeJSONPart(writer *multipart.Writer, contentType string, body Body, compressed bool) (err error) {
bytes, err := json.Marshal(body)
if err != nil {
return err
}
if len(bytes) < kMinCompressedJSONSize {
compressed = false
}
partHeaders := textproto.MIMEHeader{}
partHeaders.Set("Content-Type", contentType)
if compressed {
partHeaders.Set("Content-Encoding", "gzip")
}
part, err := writer.CreatePart(partHeaders)
if err != nil {
return err
}
if compressed {
gz := gzip.NewWriter(part)
_, err = gz.Write(bytes)
gz.Close()
} else {
_, err = part.Write(bytes)
}
return
}
示例3: checkContentType
func checkContentType(h textproto.MIMEHeader, expected string) error {
ctype := h.Get("Content-Type")
if ctype != expected {
return errors.Errorf("expected Content-Type %q, got %q", expected, ctype)
}
return nil
}
示例4: newEntity
func newEntity(h textproto.MIMEHeader, r io.Reader, shared *sharedData) (*Entity, error) {
contType := h.Get("Content-Type")
if contType == "" {
return &Entity{
Header: h,
body: &SinglepartBody{Reader: r},
shared: shared,
}, nil
}
mediaType, params, err := mime.ParseMediaType(contType)
if err != nil {
return nil, err
}
if !strings.HasPrefix(mediaType, "multipart/") {
return &Entity{
Header: h,
body: &SinglepartBody{Reader: r},
shared: shared,
}, nil
}
boundary, ok := params["boundary"]
if !ok {
return nil, fmt.Errorf("Boundary not found in Content-Type field: %v", contType)
}
return &Entity{
Header: h,
body: &MultipartBody{multipart.NewReader(r, boundary)},
shared: shared,
}, nil
}
示例5: WriteMultipartDocument
// Writes a revision to a MIME multipart writer, encoding large attachments as separate parts.
func (db *Database) WriteMultipartDocument(body Body, writer *multipart.Writer, compress bool) {
// First extract the attachments that should follow:
following := []attInfo{}
for name, value := range BodyAttachments(body) {
meta := value.(map[string]interface{})
var info attInfo
info.contentType, _ = meta["content_type"].(string)
info.data, _ = decodeAttachment(meta["data"])
if info.data != nil && len(info.data) > kMaxInlineAttachmentSize {
info.name = name
following = append(following, info)
delete(meta, "data")
meta["follows"] = true
}
}
// Write the main JSON body:
writeJSONPart(writer, "application/json", body, compress)
// Write the following attachments
for _, info := range following {
partHeaders := textproto.MIMEHeader{}
if info.contentType != "" {
partHeaders.Set("Content-Type", info.contentType)
}
partHeaders.Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", info.name))
part, _ := writer.CreatePart(partHeaders)
part.Write(info.data)
}
}
示例6: ValidateSingle
// Very Useful for AJAX Validater that require server-side validation
func (f *Form) ValidateSingle(name, value, mime string) error {
values := Values{
name: []string{value},
}
mimeheader := textproto.MIMEHeader{}
mimeheader.Add("Content-Type", mime)
files := FileHeaders{
name: []*multipart.FileHeader{&multipart.FileHeader{
Header: mimeheader}},
}
val := &Validation{values, files, true, CurVal("")}
for _, field := range f.fields {
switch t := field.(type) {
case Label:
continue
default:
if t.GetName() == name {
return t.Validate(val)
}
}
}
return FormError(f.lang["ErrFieldDoesNotExist"])
}
示例7: handleEventMsg
//handleEventMsg processes event messages received from Freeswitch.
func (client *Client) handleEventMsg(resp textproto.MIMEHeader) error {
event := make(map[string]string)
//Check that Content-Length is numeric.
_, err := strconv.Atoi(resp.Get("Content-Length"))
if err != nil {
log.Print(logPrefix, "Invalid Content-Length", err)
return err
}
for {
//Read each line of the event and store into map.
line, err := client.eventConn.ReadLine()
if err != nil {
log.Print(logPrefix, "Event Read failure: ", err)
return err
}
if line == "" { //Empty line means end of event.
client.sendEvent(event)
return err
}
parts := strings.Split(line, ": ") //Split "Key: value"
key := parts[0]
value, err := url.QueryUnescape(parts[1])
if err != nil {
log.Print(logPrefix, "Parse failure: ", err)
return err
}
event[key] = value
}
}
示例8: mediaTypeOrDefault
func mediaTypeOrDefault(header textproto.MIMEHeader) string {
mediaType, _, err := mime.ParseMediaType(header.Get("Content-Type"))
if err != nil {
return "application/octet-stream"
}
return mediaType
}
示例9: WriteRevisionAsPart
// Adds a new part to the given multipart writer, containing the given revision.
// The revision will be written as a nested multipart body if it has attachments.
func (db *Database) WriteRevisionAsPart(revBody Body, isError bool, compressPart bool, writer *multipart.Writer) error {
partHeaders := textproto.MIMEHeader{}
docID, _ := revBody["_id"].(string)
revID, _ := revBody["_rev"].(string)
if len(docID) > 0 {
partHeaders.Set("X-Doc-ID", docID)
partHeaders.Set("X-Rev-ID", revID)
}
if hasInlineAttachments(revBody) {
// Write as multipart, including attachments:
// OPT: Find a way to do this w/o having to buffer the MIME body in memory!
var buffer bytes.Buffer
docWriter := multipart.NewWriter(&buffer)
contentType := fmt.Sprintf("multipart/related; boundary=%q",
docWriter.Boundary())
partHeaders.Set("Content-Type", contentType)
db.WriteMultipartDocument(revBody, docWriter, compressPart)
docWriter.Close()
content := bytes.TrimRight(buffer.Bytes(), "\r\n")
part, err := writer.CreatePart(partHeaders)
if err == nil {
_, err = part.Write(content)
}
return err
} else {
// Write as JSON:
contentType := "application/json"
if isError {
contentType += `; error="true"`
}
return writeJSONPart(writer, contentType, revBody, compressPart)
}
}
示例10: CreateMailMessage
// CreateMailMessage creates a (plain) SMTP email with body and
// optional attachments.
func CreateMailMessage(body []byte, att []*MailAttachment) ([]byte, error) {
buf := new(bytes.Buffer)
wrt := multipart.NewWriter(buf)
buf.WriteString(
"MIME-Version: 1.0\n" +
"Content-Type: multipart/mixed;\n" +
" boundary=\"" + wrt.Boundary() + "\"\n\n" +
"This is a multi-part message in MIME format.\n")
hdr := textproto.MIMEHeader{}
hdr.Set("Content-Type", "text/plain; charset=ISO-8859-15")
hdr.Set("Content-Transfer-Encoding", "utf-8")
pw, err := wrt.CreatePart(hdr)
if err != nil {
return nil, err
}
pw.Write(body)
for _, a := range att {
pw, err = wrt.CreatePart(a.Header)
if err != nil {
return nil, err
}
pw.Write(a.Data)
}
wrt.Close()
return buf.Bytes(), nil
}
示例11: renderPartsToWriter
func renderPartsToWriter(parts cloudInitParts, writer io.Writer) error {
mimeWriter := multipart.NewWriter(writer)
defer mimeWriter.Close()
writer.Write([]byte(fmt.Sprintf("Content-Type: multipart/mixed; boundary=\"%s\"\n", mimeWriter.Boundary())))
for _, part := range parts {
header := textproto.MIMEHeader{}
if part.ContentType == "" {
header.Set("Content-Type", "text/plain")
} else {
header.Set("Content-Type", part.ContentType)
}
if part.Filename != "" {
header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, part.Filename))
}
if part.MergeType != "" {
header.Set("X-Merge-Type", part.MergeType)
}
partWriter, err := mimeWriter.CreatePart(header)
if err != nil {
return err
}
_, err = partWriter.Write([]byte(part.Content))
if err != nil {
return err
}
}
return nil
}
示例12: parseMIMEParts
// parseMIMEParts will recursively walk a MIME entity and return a []mime.Part containing
// each (flattened) mime.Part found.
// It is important to note that there are no limits to the number of recursions, so be
// careful when parsing unknown MIME structures!
func parseMIMEParts(hs textproto.MIMEHeader, b io.Reader) ([]*part, error) {
var ps []*part
// If no content type is given, set it to the default
if _, ok := hs["Content-Type"]; !ok {
hs.Set("Content-Type", defaultContentType)
}
ct, params, err := mime.ParseMediaType(hs.Get("Content-Type"))
if err != nil {
return ps, err
}
// If it's a multipart email, recursively parse the parts
if strings.HasPrefix(ct, "multipart/") {
if _, ok := params["boundary"]; !ok {
return ps, ErrMissingBoundary
}
mr := multipart.NewReader(b, params["boundary"])
for {
var buf bytes.Buffer
p, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return ps, err
}
if _, ok := p.Header["Content-Type"]; !ok {
p.Header.Set("Content-Type", defaultContentType)
}
subct, _, err := mime.ParseMediaType(p.Header.Get("Content-Type"))
if strings.HasPrefix(subct, "multipart/") {
sps, err := parseMIMEParts(p.Header, p)
if err != nil {
return ps, err
}
ps = append(ps, sps...)
} else {
// Otherwise, just append the part to the list
// Copy the part data into the buffer
if _, err := io.Copy(&buf, p); err != nil {
return ps, err
}
ps = append(ps, &part{body: buf.Bytes(), header: p.Header})
}
}
} else {
// If it is not a multipart email, parse the body content as a single "part"
var buf bytes.Buffer
if _, err := io.Copy(&buf, b); err != nil {
return ps, err
}
ps = append(ps, &part{body: buf.Bytes(), header: hs})
}
return ps, nil
}
示例13: appendPart
func appendPart(w *multipart.Writer, headers func(h textproto.MIMEHeader), body string) {
if body == "" {
return
}
h := textproto.MIMEHeader{}
h.Set("Content-Transfer-Encoding", "quoted-printable")
headers(h)
partW, err := w.CreatePart(h)
log.Panice(err, "create MIME part")
quoW := quotedprintable.NewWriter(partW)
defer quoW.Close()
io.WriteString(quoW, body)
}
示例14: handleAPIMsg
//handleAPIMsg processes API response messages received from Freeswitch.
func (client *Client) handleAPIMsg(resp textproto.MIMEHeader) error {
//Check that Content-Length is numeric.
length, err := strconv.Atoi(resp.Get("Content-Length"))
if err != nil {
log.Print(logPrefix, "Invalid Content-Length", err)
client.sendCmdRes(cmdRes{body: "", err: err}, true)
return err
}
//Read Content-Length bytes into a buffer and convert to string.
buf := make([]byte, length)
if _, err = io.ReadFull(client.eventConn.R, buf); err != nil {
log.Print(logPrefix, "API Read failure: ", err)
}
client.sendCmdRes(cmdRes{body: string(buf), err: err}, true)
return err
}
示例15: createFormFile
func createFormFile(writer *multipart.Writer, fieldname, filename string) {
// Try to open the file.
file, err := os.Open(filename)
if err != nil {
panic(err)
}
defer file.Close()
// Create a new form-data header with the provided field name and file name.
// Determine Content-Type of the file by its extension.
h := textproto.MIMEHeader{}
h.Set("Content-Disposition", fmt.Sprintf(
`form-data; name="%s"; filename="%s"`,
escapeQuotes(fieldname),
escapeQuotes(filepath.Base(filename)),
))
h.Set("Content-Type", "application/octet-stream")
if ct := mime.TypeByExtension(filepath.Ext(filename)); ct != "" {
h.Set("Content-Type", ct)
}
part, err := writer.CreatePart(h)
if err != nil {
panic(err)
}
// Copy the content of the file we have opened not reading the whole
// file into memory.
_, err = io.Copy(part, file)
if err != nil {
panic(err)
}
}