Data URL Schemes in Golang
- Go 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .golangci.yml | ||
| .markdownlint-cli2.jsonc | ||
| dataurl.go | ||
| dataurl_test.go | ||
| doc.go | ||
| go.mod | ||
| lex.go | ||
| LICENSE | ||
| README.md | ||
| rfc2396.go | ||
| rfc2396_test.go | ||
Data URL Schemes for Go
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.Readerfor 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 rtlabs.tech/datauri
Usage
package main
import (
"rtlabs.tech/datauri"
"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)
}
}
Copyright and License
Code and Documentation Copyright © 1994-2026, Stephen Kapp and Reaper Technologies Limited. All Rights Reserved.