datauri

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2025 License: MIT Imports: 12 Imported by: 0

README

datauri

Go Reference

Data URI Schemes for Go

This package parses and generates Data URI Schemes for the Go language, according to RFC 2397.

Data URIs are small chunks of data commonly used in browsers to display inline data, typically like small images, or when you use the FileReader API of the browser.

Command

Use the datauri command to encode/decode data URI streams.

Install it with go install github.com/invopop/datauri/cmd/datauri@latest.

LICENSE

Forked from RealImage/dataurl, which in turn is forked from vincent-petithory/dataurl with contributions from MagicalTux/dataurl.

Datauri is available under the terms of the MIT license.

Documentation

Overview

Package datauri parses Data URI Schemes according to RFC 2397 (http://tools.ietf.org/html/rfc2397).

Data URIs are small chunks of data commonly used in browsers to display inline data, typically like small images, or when you use the FileReader API of the browser.

A dataurl looks like:

data:text/plain;charset=utf-8,A%20brief%20note

Or, with base64 encoding:

data:image/vnd.microsoft.icon;name=golang%20favicon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAD///8AVE44//7hdv/+4Xb//uF2//7hdv/+4Xb//uF2//7hdv/+4Xb//uF2//7hdv/+4Xb/
/uF2/1ROOP////8A////AFROOP/+4Xb//uF2//7hdv/+4Xb//uF2//7hdv/+4Xb//uF2//7hdv/+
...
/6CcjP97c07/e3NO/1dOMf9BOiX/TkUn/2VXLf97c07/e3NO/6CcjP/h4uX/////AP///wD///8A
////AP///wD///8A////AP///wDq6/H/3N/j/9fZ3f/q6/H/////AP///wD///8A////AP///wD/
//8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAA==

Common functions are Decode and DecodeString to obtain a DataURI, and DataURI.String() and DataURI.WriteTo to generate a Data URI string.

Index

Examples

Constants

View Source
const (
	// EncodingBase64 is base64 encoding for the data uri
	EncodingBase64 = "base64"
	// EncodingASCII is ascii encoding for the data uri
	EncodingASCII = "ascii"
)

Variables

This section is empty.

Functions

func EncodeBytes

func EncodeBytes(data []byte) string

EncodeBytes encodes the data bytes into a Data URI string, using base 64 encoding.

The media type of data is detected using http.DetectContentType.

func Escape

func Escape(data []byte) string

Escape implements URL escaping, as defined in RFC 2397 (http://tools.ietf.org/html/rfc2397). It differs a bit from net/url's QueryEscape and QueryUnescape, e.g how spaces are treated (+ instead of %20):

Only ASCII chars are allowed. Reserved chars are escaped to their %xx form. Unreserved chars are [a-z], [A-Z], [0-9], and -_.!~*\().

Example
fmt.Println(Escape([]byte("A brief note")))
Output:

A%20brief%20note

func EscapeString

func EscapeString(s string) string

EscapeString is like Escape, but taking a string as argument.

Example
fmt.Println(EscapeString("A brief note"))
Output:

A%20brief%20note

func Unescape

func Unescape(s string) ([]byte, error)

Unescape unescapes a character sequence escaped with Escape(String?).

Example
data, err := Unescape("A%20brief%20note")
if err != nil {
	// can fail e.g if incorrect escaped sequence
	fmt.Println(err)
	return
}
fmt.Println(string(data))
Output:

A brief note

func UnescapeToString

func UnescapeToString(s string) (string, error)

UnescapeToString is like Unescape, but returning a string.

Example
s, err := UnescapeToString("A%20brief%20note")
if err != nil {
	// can fail e.g if incorrect escaped sequence
	fmt.Println(err)
	return
}
fmt.Println(s)
Output:

A brief note

Types

type DataURI

type DataURI struct {
	MediaType
	Encoding string
	Data     []byte
}

DataURI is the combination of a MediaType describing the type of its Data.

func Decode

func Decode(r io.Reader) (*DataURI, error)

Decode decodes a Data URI scheme from a io.Reader.

Example
r, err := http.NewRequest(
	"POST",
	"/",
	strings.NewReader(
		`data:image/vnd.microsoft.icon;name=golang%20favicon;base64,`+golangFavicon,
	),
)
if err != nil {
	fmt.Println(err)
	return
}

var dataURI *DataURI
h := func(_ http.ResponseWriter, r *http.Request) {
	var err error
	dataURI, err = Decode(r.Body)
	defer r.Body.Close() //nolint:errcheck
	if err != nil {
		fmt.Println(err)
	}
}
w := httptest.NewRecorder()
h(w, r)
fmt.Printf("%s: %s", dataURI.Params["name"], dataURI.ContentType())
Output:

golang favicon: image/vnd.microsoft.icon

func DecodeString

func DecodeString(s string) (*DataURI, error)

DecodeString decodes a Data URI scheme string.

Example
dataURI, err := DecodeString(`data:text/plain;charset=utf-8;base64,aGV5YQ==`)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("%s, %s", dataURI.ContentType(), string(dataURI.Data))
Output:

text/plain, heya

func New

func New(data []byte, mediatype string, paramPairs ...string) *DataURI

New returns a new DataURI initialized with data and a MediaType parsed from mediatype and paramPairs. mediatype must be of the form "type/subtype" or it will panic. paramPairs must have an even number of elements or it will panic. For more complex DataURI, initialize a DataURI struct. The DataURI is initialized with base64 encoding.

func (*DataURI) MarshalText

func (du *DataURI) MarshalText() ([]byte, error)

MarshalText writes du as a Data URI

func (*DataURI) String

func (du *DataURI) String() string

String implements the Stringer interface.

Note: it doesn't guarantee the returned string is equal to the initial source string that was used to create this DataURI. The reasons for that are:

  • Insertion of default values for MediaType that were maybe not in the initial string,
  • Various ways to encode the MediaType parameters (quoted string or uri encoded string, the latter is used),

func (*DataURI) UnmarshalText

func (du *DataURI) UnmarshalText(text []byte) error

UnmarshalText decodes a Data URI string and sets it to *du

func (*DataURI) WriteTo

func (du *DataURI) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements the WriterTo interface. See the note about String().

type MediaType

type MediaType struct {
	Type    string
	Subtype string
	Params  map[string]string
}

MediaType is the combination of a media type, a media subtype and optional parameters.

func (*MediaType) ContentType

func (mt *MediaType) ContentType() string

ContentType returns the content type of the datauri's data, in the form type/subtype.

func (*MediaType) String

func (mt *MediaType) String() string

String implements the Stringer interface.

Params values are escaped with the Escape function, rather than in a quoted string.

Directories

Path Synopsis
cmd
dataurl command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL