From 5eecd85d7da368727316e5bc4d0e4f35fbeadcf2 Mon Sep 17 00:00:00 2001 From: ivmorski Date: Fri, 9 Oct 2026 14:16:53 +0200 Subject: [PATCH] Write a file under JSON as base64 --- pkg/runtime/httpserver/write.go | 18 ++++++++++++------ pkg/runtime/httpserver/write_test.go | 2 ++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/pkg/runtime/httpserver/write.go b/pkg/runtime/httpserver/write.go index 9a1b4ec..38791fa 100644 --- a/pkg/runtime/httpserver/write.go +++ b/pkg/runtime/httpserver/write.go @@ -38,20 +38,26 @@ func (wr Writer) Write(w http.ResponseWriter, status int, headers http.Header, b w.Header()[key] = values } - switch b := body.(type) { - case nil: + if body == nil { w.WriteHeader(status) return nil - case runtime.File: - return writeFile(w, status, b) - case *runtime.File: - return writeFile(w, status, *b) } mediaType := runtime.ContentType(w.Header()) if runtime.IsJSON(mediaType) { return wr.writeJSON(w, status, body) } + + switch b := body.(type) { + case runtime.File: + return writeFile(w, status, b) + case *runtime.File: + if b == nil { + w.WriteHeader(status) + return nil + } + return writeFile(w, status, *b) + } if data, ok := rawBody(body); ok { return writeBytes(w, status, data) } diff --git a/pkg/runtime/httpserver/write_test.go b/pkg/runtime/httpserver/write_test.go index 2541855..95ff6c1 100644 --- a/pkg/runtime/httpserver/write_test.go +++ b/pkg/runtime/httpserver/write_test.go @@ -72,6 +72,8 @@ func TestWrite(t *testing.T) { {name: "File", body: runtime.NewFile([]byte("data"), "a.bin", "image/png"), wantContentType: "image/png", wantBody: "data"}, {name: "File pointer", body: runtime.Ptr(runtime.NewFileReader(strings.NewReader("data"), "a", "", -1)), wantContentType: "", wantBody: "data"}, {name: "A string under JSON", headers: http.Header{"Content-Type": {"application/json"}}, body: runtime.Ptr("hi"), wantContentType: "application/json", wantBody: `"hi"`}, + {name: "A file under JSON", headers: http.Header{"Content-Type": {"application/json"}}, body: runtime.Ptr(runtime.NewFile([]byte("hi"), "", "")), wantContentType: "application/json", wantBody: `"aGk="`}, + {name: "A nil file", headers: http.Header{"Content-Type": {"image/png"}}, body: (*runtime.File)(nil), wantContentType: "image/png"}, {name: "JSON with parameters", headers: http.Header{"Content-Type": {"application/json; charset=utf-8"}}, body: map[string]int{"a": 1}, wantContentType: "application/json; charset=utf-8", wantBody: `{"a":1}`}, {name: "A defined string as it is", headers: http.Header{"Content-Type": {"text/plain"}}, body: runtime.Ptr(note("hi")), wantContentType: "text/plain", wantBody: "hi"}, {name: "A nil pointer without JSON", headers: http.Header{"Content-Type": {"application/xml"}}, body: (*struct{})(nil), wantContentType: "application/xml"},