impr: backward-compatible compliance with rfc 2397
This commit is contained in:
@@ -72,24 +72,31 @@ func ReadJson[T any](path string) (T, error) {
|
||||
|
||||
// WriteFile writes the file to disk.
|
||||
// The content can be text or binary (encoded as a data URL),
|
||||
// e.g. data:;base64,MTIz
|
||||
// e.g. data:application/octet-stream;base64,MTIz
|
||||
func WriteFile(path, content string, perm fs.FileMode) (err error) {
|
||||
var data []byte
|
||||
// TODO: only check for "data:;base64," to comply with RFC 2397.
|
||||
// Remove the "data:" check after the snippet reaches 0.16.
|
||||
if strings.HasPrefix(content, "data:") || strings.HasPrefix(content, "data:;base64,") {
|
||||
// data-url encoded file
|
||||
_, encoded, found := strings.Cut(content, ",")
|
||||
if !found {
|
||||
return errors.New("invalid data-url encoding")
|
||||
}
|
||||
data, err = base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if !strings.HasPrefix(content, "data:") {
|
||||
// text file
|
||||
data = []byte(content)
|
||||
return os.WriteFile(path, data, perm)
|
||||
}
|
||||
|
||||
// data-url encoded file
|
||||
meta, encoded, found := strings.Cut(content, ",")
|
||||
if !found {
|
||||
return errors.New("invalid data-url encoding")
|
||||
}
|
||||
|
||||
if !strings.HasSuffix(meta, "base64") {
|
||||
// no need to decode
|
||||
data = []byte(encoded)
|
||||
return os.WriteFile(path, data, perm)
|
||||
}
|
||||
|
||||
// decode base64-encoded data
|
||||
data, err = base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, data, perm)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user