File: dataurl.go

package info (click to toggle)
golang-github-evanw-esbuild 0.25.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,184 kB
  • sloc: javascript: 28,602; makefile: 856; sh: 17
file content (76 lines) | stat: -rw-r--r-- 1,695 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package resolver

import (
	"encoding/base64"
	"fmt"
	"net/url"
	"strings"
)

type DataURL struct {
	mimeType string
	data     string
	isBase64 bool
}

func ParseDataURL(url string) (parsed DataURL, ok bool) {
	if strings.HasPrefix(url, "data:") {
		if comma := strings.IndexByte(url, ','); comma != -1 {
			parsed.mimeType = url[len("data:"):comma]
			parsed.data = url[comma+1:]
			if strings.HasSuffix(parsed.mimeType, ";base64") {
				parsed.mimeType = parsed.mimeType[:len(parsed.mimeType)-len(";base64")]
				parsed.isBase64 = true
			}
			ok = true
		}
	}
	return
}

type MIMEType uint8

const (
	MIMETypeUnsupported MIMEType = iota
	MIMETypeTextCSS
	MIMETypeTextJavaScript
	MIMETypeApplicationJSON
)

func (parsed DataURL) DecodeMIMEType() MIMEType {
	// Remove things like ";charset=utf-8"
	mimeType := parsed.mimeType
	if semicolon := strings.IndexByte(mimeType, ';'); semicolon != -1 {
		mimeType = mimeType[:semicolon]
	}

	// Hard-code a few supported types
	switch mimeType {
	case "text/css":
		return MIMETypeTextCSS
	case "text/javascript":
		return MIMETypeTextJavaScript
	case "application/json":
		return MIMETypeApplicationJSON
	default:
		return MIMETypeUnsupported
	}
}

func (parsed DataURL) DecodeData() (string, error) {
	// Try to read base64 data
	if parsed.isBase64 {
		bytes, err := base64.StdEncoding.DecodeString(parsed.data)
		if err != nil {
			return "", fmt.Errorf("could not decode base64 data: %s", err.Error())
		}
		return string(bytes), nil
	}

	// Try to read percent-escaped data
	content, err := url.PathUnescape(parsed.data)
	if err != nil {
		return "", fmt.Errorf("could not decode percent-escaped data: %s", err.Error())
	}
	return content, nil
}