From 985d4a6141b303710c53c8d2de97eedfc2bd13bb Mon Sep 17 00:00:00 2001 From: Tom Fleet Date: Mon, 22 Jun 2026 17:26:58 +0100 Subject: [PATCH] Add a .JSON() method for convenience (#16) * Add a .JSON() method for convenience * Renormalise testdata EOL --- .gitattributes | 2 +- problem.go | 31 +++++- problem_test.go | 105 +++++++++++++++++- testdata/TestJSONMethod/empty-new.json | 1 + testdata/{ => TestJSONMethod}/empty.json | 0 testdata/TestJSONMethod/no-extra.json | 1 + testdata/TestJSONMethod/with-extra.json | 1 + testdata/{ => TestProblemJSON}/empty-new.json | 0 testdata/TestProblemJSON/empty.json | 1 + testdata/{ => TestProblemJSON}/no-extra.json | 0 .../{ => TestProblemJSON}/with-extra.json | 0 11 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 testdata/TestJSONMethod/empty-new.json rename testdata/{ => TestJSONMethod}/empty.json (100%) create mode 100644 testdata/TestJSONMethod/no-extra.json create mode 100644 testdata/TestJSONMethod/with-extra.json rename testdata/{ => TestProblemJSON}/empty-new.json (100%) create mode 100644 testdata/TestProblemJSON/empty.json rename testdata/{ => TestProblemJSON}/no-extra.json (100%) rename testdata/{ => TestProblemJSON}/with-extra.json (100%) diff --git a/.gitattributes b/.gitattributes index 6ec62ae..8ba88b9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,4 +3,4 @@ # Force LF even on windows for testdata, means comparisons don't fail just # because of line endings -**/testdata/* text eol=lf +**/testdata/** text eol=lf diff --git a/problem.go b/problem.go index c35513c..59918d3 100644 --- a/problem.go +++ b/problem.go @@ -34,6 +34,9 @@ import ( // ContentType is the value for the HTTP 'Content-Type' header that signifies an RFC-7807 problem. const ContentType = "application/problem+json" +// errResponse is what gets marshalled to response writers if for some reason JSON marshalling fails. +const errResponse = `{"type":"about:blank","detail":"Failed to generate error response","status":500}` + // Problem represents an [RFC-7807] problem. // // [RFC-7807]: https://datatracker.ietf.org/doc/html/rfc7807 @@ -207,10 +210,36 @@ func (p Problem) Respond(w http.ResponseWriter) { if err := json.MarshalWrite(w, p, json.Deterministic(true)); err != nil { w.WriteHeader(http.StatusInternalServerError) - fmt.Fprint(w, `{"type":"about:blank","detail":"Failed to generate error response","status":500}`) + fmt.Fprint(w, errResponse) } } +// JSON returns the JSON encoding of the calling [Problem]. +// +// prob := problem.Problem{ +// Title: "Uh oh", +// Detail: "A thing went wrong", +// Status: http.StatusTeapot, +// } +// +// prob.JSON() +// +// If JSON marshalling fails for some reason, the following is returned: +// +// { +// "title": "about:blank", +// "detail": "Failed to generate problem response", +// "status": 500 +// } +func (p Problem) JSON() []byte { + content, err := json.Marshal(p, json.Deterministic(true)) + if err != nil { + return []byte(errResponse) + } + + return content +} + // Option is a functional option passed to [New] in order to modify a [Problem]. type Option func(*Problem) diff --git a/problem_test.go b/problem_test.go index bb0dbd7..e7bb6a4 100644 --- a/problem_test.go +++ b/problem_test.go @@ -107,7 +107,110 @@ func TestProblemJSON(t *testing.T) { got, err := json.Marshal(tt.problem, jsontext.WithIndent(" "), json.Deterministic(true)) test.Ok(t, err) - golden := filepath.Join("testdata", tt.golden) + golden := filepath.Join("testdata", "TestProblemJSON", tt.golden) + + if *update { + test.Ok(t, os.WriteFile(golden, got, 0o644)) + } + + want, err := os.ReadFile(golden) + test.Ok(t, err) + + test.DiffBytes(t, got, want) + }) + } +} + +func TestJSONMethod(t *testing.T) { + test.ColorEnabled(os.Getenv("CI") == "") // Force colour for diffs locally + + tests := []struct { + name string + golden string + problem problem.Problem + }{ + { + name: "empty", + problem: problem.Problem{}, + golden: "empty.json", + }, + { + name: "empty new", + problem: problem.New(), + golden: "empty-new.json", // Not the same as empty as `type` defaults to "about:blank" + }, + { + name: "no extra", + problem: problem.Problem{ + Type: "https://example.com/probs/out-of-credit", + Title: "Not enough credit", + Detail: "Your current balance is 30, but that costs 50", + Instance: "/account/12345/msgs/abc", + Status: http.StatusBadRequest, + }, + golden: "no-extra.json", + }, + { + name: "no extra new", + problem: problem.New( + problem.Type("https://example.com/probs/out-of-credit"), + problem.Title("Not enough credit"), + problem.Detail("Your current balance is 30, but that costs 50"), + problem.Instance("/account/12345/msgs/abc"), + problem.Status(http.StatusBadRequest), + ), + golden: "no-extra.json", // Should serialize exactly the same + }, + { + name: "with extra", + problem: problem.Problem{ + Type: "https://example.com/probs/out-of-credit", + Title: "Not enough credit", + Detail: "Your current balance is 30, but that costs 50", + Instance: "/account/12345/msgs/abc", + Status: http.StatusBadRequest, + Extra: map[string]any{ + "balance": 30, + "accounts": []string{"/accounts/12345", "/accounts/67890"}, + }, + }, + golden: "with-extra.json", + }, + { + name: "with extra new", + problem: problem.New( + problem.Type("https://example.com/probs/out-of-credit"), + problem.Title("Not enough credit"), + problem.Detail("Your current balance is 30, but that costs 50"), + problem.Instance("/account/12345/msgs/abc"), + problem.Status(http.StatusBadRequest), + problem.Extra("balance", 30), + problem.Extra("accounts", []string{"/accounts/12345", "/accounts/67890"}), + ), + golden: "with-extra.json", // Should serialize exactly the same + }, + { + name: "with extra map new", + problem: problem.New( + problem.Type("https://example.com/probs/out-of-credit"), + problem.Title("Not enough credit"), + problem.Detail("Your current balance is 30, but that costs 50"), + problem.Instance("/account/12345/msgs/abc"), + problem.Status(http.StatusBadRequest), + problem.ExtraMap(map[string]any{ + "balance": 30, + "accounts": []string{"/accounts/12345", "/accounts/67890"}, + }), + ), + golden: "with-extra.json", // Should serialize exactly the same + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.problem.JSON() + + golden := filepath.Join("testdata", "TestJSONMethod", tt.golden) if *update { test.Ok(t, os.WriteFile(golden, got, 0o644)) diff --git a/testdata/TestJSONMethod/empty-new.json b/testdata/TestJSONMethod/empty-new.json new file mode 100644 index 0000000..7447e58 --- /dev/null +++ b/testdata/TestJSONMethod/empty-new.json @@ -0,0 +1 @@ +{"type":"about:blank"} \ No newline at end of file diff --git a/testdata/empty.json b/testdata/TestJSONMethod/empty.json similarity index 100% rename from testdata/empty.json rename to testdata/TestJSONMethod/empty.json diff --git a/testdata/TestJSONMethod/no-extra.json b/testdata/TestJSONMethod/no-extra.json new file mode 100644 index 0000000..5f992d7 --- /dev/null +++ b/testdata/TestJSONMethod/no-extra.json @@ -0,0 +1 @@ +{"type":"https://example.com/probs/out-of-credit","title":"Not enough credit","detail":"Your current balance is 30, but that costs 50","instance":"/account/12345/msgs/abc","status":400} \ No newline at end of file diff --git a/testdata/TestJSONMethod/with-extra.json b/testdata/TestJSONMethod/with-extra.json new file mode 100644 index 0000000..c87d8bf --- /dev/null +++ b/testdata/TestJSONMethod/with-extra.json @@ -0,0 +1 @@ +{"type":"https://example.com/probs/out-of-credit","title":"Not enough credit","detail":"Your current balance is 30, but that costs 50","instance":"/account/12345/msgs/abc","status":400,"accounts":["/accounts/12345","/accounts/67890"],"balance":30} \ No newline at end of file diff --git a/testdata/empty-new.json b/testdata/TestProblemJSON/empty-new.json similarity index 100% rename from testdata/empty-new.json rename to testdata/TestProblemJSON/empty-new.json diff --git a/testdata/TestProblemJSON/empty.json b/testdata/TestProblemJSON/empty.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/testdata/TestProblemJSON/empty.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/testdata/no-extra.json b/testdata/TestProblemJSON/no-extra.json similarity index 100% rename from testdata/no-extra.json rename to testdata/TestProblemJSON/no-extra.json diff --git a/testdata/with-extra.json b/testdata/TestProblemJSON/with-extra.json similarity index 100% rename from testdata/with-extra.json rename to testdata/TestProblemJSON/with-extra.json -- knotmirror 0.0.1