2023-03-31 11:50:26 -06:00
|
|
|
// Package data provides operations to deal with arbitrary data and MIME types.
|
2023-02-01 23:47:01 -07:00
|
|
|
package data
|
|
|
|
|
|
|
|
import "io"
|
2023-03-27 18:44:39 -06:00
|
|
|
import "bytes"
|
2023-02-01 23:47:01 -07:00
|
|
|
|
|
|
|
// Data represents arbitrary polymorphic data that can be used for data transfer
|
|
|
|
// between applications.
|
2023-03-30 16:42:40 -06:00
|
|
|
type Data map[Mime] io.ReadSeekCloser
|
2023-02-01 23:47:01 -07:00
|
|
|
|
|
|
|
// Mime represents a MIME type.
|
|
|
|
type Mime struct {
|
|
|
|
// Type is the first half of the MIME type, and Subtype is the second
|
|
|
|
// half. The separating slash is not included in either. For example,
|
|
|
|
// text/html becomes:
|
|
|
|
// Mime { Type: "text", Subtype: "html" }
|
|
|
|
Type, Subtype string
|
|
|
|
}
|
|
|
|
|
2023-03-27 23:00:54 -06:00
|
|
|
// M is shorthand for creating a MIME type.
|
|
|
|
func M (ty, subtype string) Mime {
|
|
|
|
return Mime { ty, subtype }
|
|
|
|
}
|
|
|
|
|
|
|
|
// String returns the string representation of the MIME type.
|
|
|
|
func (mime Mime) String () string {
|
|
|
|
return mime.Type + "/" + mime.Subtype
|
|
|
|
}
|
|
|
|
|
2023-02-01 23:47:01 -07:00
|
|
|
var MimePlain = Mime { "text", "plain" }
|
|
|
|
|
|
|
|
var MimeFile = Mime { "text", "uri-list" }
|
2023-03-27 18:44:39 -06:00
|
|
|
|
|
|
|
type byteReadCloser struct { *bytes.Reader }
|
|
|
|
func (byteReadCloser) Close () error { return nil }
|
|
|
|
|
|
|
|
// Text returns plain text Data given a string.
|
|
|
|
func Text (text string) Data {
|
2023-03-28 22:50:23 -06:00
|
|
|
return Bytes(MimePlain, []byte(text))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bytes constructs a Data given a buffer and a mime type.
|
|
|
|
func Bytes (mime Mime, buffer []byte) Data {
|
2023-03-27 18:44:39 -06:00
|
|
|
return Data {
|
2023-03-28 22:50:23 -06:00
|
|
|
mime: byteReadCloser { bytes.NewReader(buffer) },
|
2023-03-27 18:44:39 -06:00
|
|
|
}
|
|
|
|
}
|
2023-03-28 22:50:23 -06:00
|
|
|
|
|
|
|
// Merge combines several Datas together. If multiple Datas provide a reader for
|
|
|
|
// the same mime type, the ones further on in the list will take precedence.
|
|
|
|
func Merge (individual ...Data) (combined Data) {
|
|
|
|
for _, data := range individual {
|
|
|
|
for mime, reader := range data {
|
|
|
|
combined[mime] = reader
|
|
|
|
}}
|
|
|
|
return
|
|
|
|
}
|