Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Go CI
on:
pull_request:
paths: ['go/**', 'spec/**', 'conformance/**', '.github/workflows/go.yml']
push:
branches: [main]
paths: ['go/**', 'spec/**', 'conformance/**', '.github/workflows/go.yml']
workflow_dispatch:
permissions:
contents: read
defaults:
run:
working-directory: go
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
matrix:
go: ['1.26.x', 'stable']
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with:
go-version: ${{ matrix.go }}
cache: false
- run: test -z "$(gofmt -l .)"
- run: go vet ./...
- run: go test -mod=readonly -race ./...
- run: go mod verify
- if: matrix.go == 'stable'
run: go run honnef.co/go/tools/cmd/staticcheck@v0.8.2 ./...
- if: matrix.go == 'stable'
run: go run golang.org/x/vuln/cmd/govulncheck@v1.10.0 ./...
13 changes: 13 additions & 0 deletions go/EXPORTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# TypeScript to Go export map

| TypeScript | Go |
| --- | --- |
| HttpError, HttpErrorOptions | Error, Options, New |
| HttpError.from(error), isHttpErrorLike | From, errors.As with *Error or an error implementing StatusCode() int |
| HttpError.from(response or problem) | FromResponse, Parse |
| HttpError.toJSON, ProblemDetails | json.Marshal through Error.MarshalJSON, with json.RawMessage extension values |
| HttpError.getResponse | Error.Write(http.ResponseWriter) |
| status, title, detail, expose, headers | StatusCode(), Title(), Detail(), Exposed(), Headers() |
| message, cause | Error(), errors.Unwrap |
| type, instance, extensions | Options fields on construction and exact-name JSON members on output |
| StatusCode, STATUS_CODE, STATUS_TEXT | int and net/http status constants. The error's Title() gives the package's canonical error title. |
14 changes: 14 additions & 0 deletions go/PORTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Porting HTTP errors to Go

The module is `github.com/udibo/http-error/go`, with package name `httperror`.
It uses the standard library and supports Go 1.26 and later.

| Decision | Reason |
| --- | --- |
| `New(Options) (*Error, error)` | A zero-value options struct describes a 500. The integer status rejects fractions at the type boundary. Pointers distinguish an omitted status, detail or expose option from an explicit zero, empty string or false. For example, use `Status: new(404)`. |
| `Error()` for diagnostics, `Detail()` for clients | A parsed detail is a diagnostic message subject to the status exposure rule. A caller may supply an explicitly public detail in the constructor. |
| `errors.As` and `Unwrap` | Wrapped HTTP errors retain their status. Converting an error with `From` or parsing an HTTP response starts a fresh set of headers. Writing an error directly preserves its own headers, including repeated fields. |
| `map[string]json.RawMessage` for extensions | Every key and JSON type survives unmarshaling, including null and case variants of standard names. Numbers retain their JSON precision. Carry large identifiers as decimal strings for I-JSON interoperability. |
| `FromResponse` and `Write` | The HTTP client owns the response body and request context. The server writes to its ordinary response writer. Applications can inspect the JSON alone with `json.Marshal`. |

Run `go test -race ./...` and `go vet ./...` from this directory. The vector tests read the repository's shared fixtures directly.
220 changes: 220 additions & 0 deletions go/conformance_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
package httperror_test

import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"reflect"
"strconv"
"testing"

httperror "github.com/udibo/http-error/go"
)

type headers http.Header

func (h *headers) UnmarshalJSON(data []byte) error {
var fields map[string]json.RawMessage
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
result := http.Header{}
for name, value := range fields {
var many []string
if err := json.Unmarshal(value, &many); err != nil {
var one string
if err := json.Unmarshal(value, &one); err != nil {
return err
}
many = []string{one}
}
for _, s := range many {
result.Add(name, s)
}
}
*h = headers(result)
return nil
}

func sameJSON(t *testing.T, got, want []byte) {
t.Helper()
decode := func(v []byte) any {
dec := json.NewDecoder(bytes.NewReader(v))
dec.UseNumber()
var result any
if err := dec.Decode(&result); err != nil {
t.Fatal(err)
}
return result
}
if !reflect.DeepEqual(decode(got), decode(want)) {
t.Fatalf("got %s, want %s", got, want)
}
}

func TestVectors(t *testing.T) {
file, err := os.Open("../conformance/vectors/problem-details.json")
if err != nil {
t.Fatal(err)
}
defer file.Close()
var vectors struct {
Description string
Serialize []struct {
Name, Error string
Input json.RawMessage
Expected struct {
Status int
Expose bool
Headers headers
Body json.RawMessage
}
}
Parse []struct {
Name string
Input struct {
Status int
Body string
Hex *string `json:"body_hex"`
}
Expected struct {
Status int
Expose bool
Title, Detail, Type, Instance string
Extensions map[string]json.RawMessage
}
}
Defaults []struct {
Status int
Title, Detail string
}
}
dec := json.NewDecoder(file)
dec.DisallowUnknownFields()
if err := dec.Decode(&vectors); err != nil {
t.Fatal(err)
}
if len(vectors.Serialize) == 0 || len(vectors.Parse) == 0 || len(vectors.Defaults) != 200 {
t.Fatal("incomplete fixture")
}
for _, v := range vectors.Serialize {
t.Run("serialize/"+v.Name, func(t *testing.T) {
var in struct {
httperror.Options
Headers headers
}
dec := json.NewDecoder(bytes.NewReader(v.Input))
dec.DisallowUnknownFields()
err := dec.Decode(&in)
// A fractional status cannot enter the typed constructor.
var typeErr *json.UnmarshalTypeError
if v.Error == "invalid status" && errors.As(err, &typeErr) && typeErr.Type == reflect.TypeFor[int]() {
return
}
if err != nil {
t.Fatal(err)
}
in.Options.Headers = http.Header(in.Headers)
e, err := httperror.New(in.Options)
if v.Error != "" {
if err == nil || v.Error != "invalid status" {
t.Fatalf("want %s, got %v", v.Error, err)
}
return
}
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
if err := e.Write(w); err != nil {
t.Fatal(err)
}
if w.Code != v.Expected.Status || e.Exposed() != v.Expected.Expose || !reflect.DeepEqual(w.Result().Header, http.Header(v.Expected.Headers)) {
t.Fatalf("status %d, expose %v, headers %v", w.Code, e.Exposed(), w.Header())
}
sameJSON(t, w.Body.Bytes(), v.Expected.Body)
})
}
for _, v := range vectors.Parse {
t.Run("parse/"+v.Name, func(t *testing.T) {
body := []byte(v.Input.Body)
if v.Input.Hex != nil {
var err error
body, err = hex.DecodeString(*v.Input.Hex)
if err != nil {
t.Fatal(err)
}
}
e := httperror.FromResponse(&http.Response{StatusCode: v.Input.Status, Body: io.NopCloser(bytes.NewReader(body))})
want := make(map[string]any)
for k, raw := range v.Expected.Extensions {
want[k] = raw
}
want["status"], want["title"], want["detail"] = v.Expected.Status, v.Expected.Title, v.Expected.Detail
if v.Expected.Type != "" {
want["type"] = v.Expected.Type
}
if v.Expected.Instance != "" {
want["instance"] = v.Expected.Instance
}
expected, err := json.Marshal(want)
if err != nil {
t.Fatal(err)
}
got, err := json.Marshal(e)
if err != nil {
t.Fatal(err)
}
sameJSON(t, got, expected)
if e.Exposed() != v.Expected.Expose {
t.Fatalf("expose = %v", e.Exposed())
}
})
}
for i, v := range vectors.Defaults {
t.Run("defaults/"+strconv.Itoa(v.Status), func(t *testing.T) {
e, err := httperror.New(httperror.Options{Status: &v.Status, Expose: new(false)})
if err != nil {
t.Fatal(err)
}
if v.Status != i+400 || e.Title() != v.Title || e.Detail() != v.Detail {
t.Fatalf("got %d %q %q", e.StatusCode(), e.Title(), e.Detail())
}
})
}
}

func TestFromAndOwnership(t *testing.T) {
cause := errors.New("database unavailable")
h := http.Header{"Set-Cookie": {"a=1", "b=2"}}
value := json.RawMessage(`"secretary"`)
e, err := httperror.New(httperror.Options{Status: new(503), Message: cause.Error(), Cause: cause, Headers: h, Extensions: map[string]json.RawMessage{"role": value}})
if err != nil {
t.Fatal(err)
}
h["Set-Cookie"][0] = "changed"
e.Headers()["Set-Cookie"][1] = "changed"
value[1] = 'x'
if !reflect.DeepEqual(e.Headers().Values("Set-Cookie"), []string{"a=1", "b=2"}) {
t.Fatal(e.Headers())
}
p := httperror.From(e)
if len(p.Headers().Values("Set-Cookie")) != 0 || !errors.Is(p, cause) || p.Detail() == cause.Error() {
t.Fatal("conversion relayed private data or lost cause")
}
b, err := json.Marshal(p)
if err != nil || !bytes.Contains(b, []byte(`"role":"secretary"`)) {
t.Fatalf("%s: %v", b, err)
}
}

func TestExplicitZeroStatus(t *testing.T) {
if _, err := httperror.New(httperror.Options{Status: new(0)}); err == nil {
t.Fatal("accepted an explicit zero status")
}
}
Loading