dataurl

package module
v0.0.0-...-66ddc08 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2022 License: MIT Imports: 12 Imported by: 0

README

Data URL Schemes for Go wercker status GoDoc

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

Data URLs 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.

Common use-cases:

  • generate a data URL out of a string, []byte, io.Reader for inclusion in HTML templates,
  • parse a data URL sent by a browser in a http.Handler, and do something with the data (save to disk, etc.)
  • ...

Install the package with:

go get github.com/vincent-petithory/dataurl

Usage

package main

import (
	"github.com/vincent-petithory/dataurl"
	"fmt"
)

func main() {
	dataURL, err := dataurl.DecodeString(`data:text/plain;charset=utf-8;base64,aGV5YQ==`)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("content type: %s, data: %s\n", dataURL.MediaType.ContentType(), string(dataURL.Data))
	// Output: content type: text/plain, data: heya
}

From a http.Handler:

func handleDataURLUpload(w http.ResponseWriter, r *http.Request) {
	dataURL, err := dataurl.Decode(r.Body)
	defer r.Body.Close()
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if dataURL.ContentType() == "image/png" {
		ioutil.WriteFile("image.png", dataURL.Data, 0644)
	} else {
		http.Error(w, "not a png", http.StatusBadRequest)
	}
}

Command

For convenience, a dataurl command is provided to encode/decode dataurl streams.

dataurl - Encode or decode dataurl data and print to standard output

Usage: dataurl [OPTION]... [FILE]

  dataurl encodes or decodes FILE or standard input if FILE is - or omitted, and prints to standard output.
  Unless -mimetype is used, when FILE is specified, dataurl will attempt to detect its mimetype using Go's mime.TypeByExtension (http://golang.org/pkg/mime/#TypeByExtension). If this fails or data is read from STDIN, the mimetype will default to application/octet-stream.

Options:
  -a=false: encode data using ascii instead of base64
  -ascii=false: encode data using ascii instead of base64
  -d=false: decode data instead of encoding
  -decode=false: decode data instead of encoding
  -m="": force the mimetype of the data to encode to this value
  -mimetype="": force the mimetype of the data to encode to this value

Contributing

Feel free to file an issue/make a pull request if you find any bug, or want to suggest enhancements.

Documentation

Overview

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

Data URLs 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 DataURL, and DataURL.String() and DataURL.WriteTo to generate a Data URL string.

Index

Examples

Constants

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

	// EncodingUtf8 is utf8 encoding for the data url ,fix(yuanjun)
	EncodingUtf8 = "utf8"
)

Variables

This section is empty.

Functions

func EncodeBytes

func EncodeBytes(data []byte) string

EncodeBytes encodes the data bytes into a Data URL 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 DataURL

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

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

func Decode

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

Decode decodes a Data URL 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 dataURL *DataURL
h := func(w http.ResponseWriter, r *http.Request) {
	var err error
	dataURL, err = Decode(r.Body)
	defer r.Body.Close()
	if err != nil {
		fmt.Println(err)
	}
}
w := httptest.NewRecorder()
h(w, r)
fmt.Printf("%s: %s", dataURL.Params["name"], dataURL.ContentType())
Output:

golang favicon: image/vnd.microsoft.icon

func DecodeString

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

DecodeString decodes a Data URL scheme string.

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

text/plain, heya

func New

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

New returns a new DataURL 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 DataURL, initialize a DataURL struct. The DataURL is initialized with base64 encoding.

func (*DataURL) MarshalText

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

MarshalText writes du as a Data URL

func (*DataURL) String

func (du *DataURL) 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 DataURL. 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 url encoded string, the latter is used),

func (*DataURL) UnmarshalText

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

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

func (*DataURL) WriteTo

func (du *DataURL) 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 dataurl'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

Jump to

Keyboard shortcuts

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