impr: comply with rfc 2397 for binary files in request

This commit is contained in:
Anton
2024-02-20 11:46:06 +05:00
parent cc3567f26e
commit 460493eeaa
2 changed files with 6 additions and 4 deletions

View File

@@ -72,10 +72,12 @@ func ReadJson[T any](path string) (T, error) {
// WriteFile writes the file to disk. // WriteFile writes the file to disk.
// The content can be text or binary (encoded as a data URL), // The content can be text or binary (encoded as a data URL),
// e.g. data:application/octet-stream;base64,MTIz // e.g. data:;base64,MTIz
func WriteFile(path, content string, perm fs.FileMode) (err error) { func WriteFile(path, content string, perm fs.FileMode) (err error) {
var data []byte var data []byte
if strings.HasPrefix(content, "data:") { // 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 // data-url encoded file
_, encoded, found := strings.Cut(content, ",") _, encoded, found := strings.Cut(content, ",")
if !found { if !found {

View File

@@ -175,7 +175,7 @@ func TestWriteFile(t *testing.T) {
t.Run("binary", func(t *testing.T) { t.Run("binary", func(t *testing.T) {
path := filepath.Join(dir, "data.bin") path := filepath.Join(dir, "data.bin")
err = WriteFile(path, "data:application/octet-stream;base64,MTIz", 0444) err = WriteFile(path, "data:;base64,MTIz", 0444)
if err != nil { if err != nil {
t.Fatalf("expected nil err, got %v", err) t.Fatalf("expected nil err, got %v", err)
} }
@@ -215,7 +215,7 @@ func TestWriteFile(t *testing.T) {
t.Run("invalid binary value", func(t *testing.T) { t.Run("invalid binary value", func(t *testing.T) {
path := filepath.Join(dir, "data.bin") path := filepath.Join(dir, "data.bin")
err = WriteFile(path, "data:application/octet-stream;base64,12345", 0444) err = WriteFile(path, "data:;base64,12345", 0444)
if err == nil { if err == nil {
t.Fatal("expected error, got nil") t.Fatal("expected error, got nil")
} }