Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add handling for RFC9457 problem responses #2

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion cookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

var cookiePool = sync.Pool{
New: func() interface{} {
New: func() any {
return &Jar{}
},
}
Expand Down
6 changes: 3 additions & 3 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type Encoder interface {

// JSONEncoder provdes encoding to JSON
type JSONEncoder struct {
v interface{}
v any
}

// Encode fulfills the Encoder interface, performing the actual encoding
Expand All @@ -34,7 +34,7 @@ func (e JSONEncoder) ContentType() string {

// YAMLEncoder provdes encoding to YAML
type YAMLEncoder struct {
v interface{}
v any
}

// Encode fulfills the Encoder interface, performing the actual encoding
Expand All @@ -49,7 +49,7 @@ func (e YAMLEncoder) ContentType() string {

// XMLEncoder provdes encoding to XML
type XMLEncoder struct {
v interface{}
v any
}

// Encode fulfills the Encoder interface, performing the actual encoding
Expand Down
33 changes: 21 additions & 12 deletions fhttpc.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package fhttpc

import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
Expand All @@ -12,6 +13,14 @@ import (
"github.com/valyala/fasthttp"
)

const (
contentTypeHeaderKey = "Content-Type"
)

var (
contentTypeHeaderValRFC9457 = []byte("application/problem+json")
)

var defaultacceptedResponseCodes = []int{
fasthttp.StatusOK,
fasthttp.StatusCreated,
Expand Down Expand Up @@ -223,19 +232,19 @@ func (r *Request) Encode(encoder Encoder) *Request {
}

// EncodeJSON encodes and sets the body for the client call using JSON encoding
func (r *Request) EncodeJSON(v interface{}) *Request {
func (r *Request) EncodeJSON(v any) *Request {
r.bodyEncoder = JSONEncoder{v}
return r
}

// EncodeYAML encodes and sets the body for the client call using YAML encoding
func (r *Request) EncodeYAML(v interface{}) *Request {
func (r *Request) EncodeYAML(v any) *Request {
r.bodyEncoder = YAMLEncoder{v}
return r
}

// EncodeXML encodes and sets the body for the client call using XML encoding
func (r *Request) EncodeXML(v interface{}) *Request {
func (r *Request) EncodeXML(v any) *Request {
r.bodyEncoder = XMLEncoder{v}
return r
}
Expand All @@ -247,19 +256,19 @@ func (r *Request) ParseFn(parseFn func(*fasthttp.Response) error) *Request {
}

// ParseJSON parses the result of the client call as JSON
func (r *Request) ParseJSON(v interface{}) *Request {
func (r *Request) ParseJSON(v any) *Request {
r.parseFn = ParseJSON(v)
return r
}

// ParseYAML parses the result of the client call as YAML
func (r *Request) ParseYAML(v interface{}) *Request {
func (r *Request) ParseYAML(v any) *Request {
r.parseFn = ParseYAML(v)
return r
}

// ParseXML parses the result of the client call as XML
func (r *Request) ParseXML(v interface{}) *Request {
func (r *Request) ParseXML(v any) *Request {
r.parseFn = ParseXML(v)
return r
}
Expand Down Expand Up @@ -499,10 +508,10 @@ func (r *Request) handleResponse(resp *fasthttp.Response) error {
return r.errorFn(resp)
}

// buf := new(bytes.Buffer)
// if _, err := io.Copy(buf, resp.Body); err != nil {
// return fmt.Errorf("failed to load body into buffer for error handling: %w", err)
// }
// Handle RFC 9457
if bytes.EqualFold(resp.Header.Peek(contentTypeHeaderKey), contentTypeHeaderValRFC9457) {
return fmt.Errorf("%d %s [body=%s]", resp.StatusCode(), resp.Header.StatusMessage(), resp.Body())
}

// Attempt to decode a generic JSON error from the response body
var extraErr HTTPError
Expand All @@ -511,7 +520,7 @@ func (r *Request) handleResponse(resp *fasthttp.Response) error {
}

// Attempt to decode the response body directly
return fmt.Errorf("%d %s [body=%.512s]", resp.StatusCode(), resp.Header.StatusMessage(), string(resp.Body()))
return fmt.Errorf("%d %s [body=%.512s]", resp.StatusCode(), resp.Header.StatusMessage(), resp.Body())
}

// if fasthttp.StatusCodeIsRedirect(resp.StatusCode()) {
Expand Down Expand Up @@ -541,7 +550,7 @@ func (r *Request) setBody(req *fasthttp.Request) (err error) {
if err != nil {
return fmt.Errorf("error encoding body: %w", err)
}
req.Header.Set("Content-Type", r.bodyEncoder.ContentType())
req.Header.Set(contentTypeHeaderKey, r.bodyEncoder.ContentType())
}

contentLength := len(bodyBytes)
Expand Down
27 changes: 17 additions & 10 deletions fhttpc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ type testCase struct {
responseFn func(resp *fasthttp.Response) error
errorFn func(resp *fasthttp.Response) error

queryParams Params
headers Params
queryParams Params
requestHeaders Params
responseHeaders Params

expectedError string

Expand Down Expand Up @@ -453,7 +454,7 @@ func TestBodySet(t *testing.T) {
}

type gobEncoder struct {
v interface{}
v any
}

// Encode fulfills the Encoder interface, performing the actual encoding
Expand Down Expand Up @@ -739,7 +740,7 @@ func TestBasicAuth(t *testing.T) {

// Set up a mock matcher
mock := NewMock(fasthttp.MethodGet, uri, testCase{
headers: map[string]string{
requestHeaders: map[string]string{
"Authorization": "Basic " + base64.RawStdEncoding.EncodeToString([]byte(user+":"+password)),
},
}).Reply(fasthttp.StatusOK)
Expand All @@ -760,7 +761,7 @@ func TestBearerAuth(t *testing.T) {

// Set up a mock matcher
mock := NewMock(fasthttp.MethodGet, uri, testCase{
headers: map[string]string{
requestHeaders: map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", token),
},
}).Reply(fasthttp.StatusOK)
Expand All @@ -781,7 +782,7 @@ func TestTokenAuth(t *testing.T) {

// Set up a mock matcher
mock := NewMock(fasthttp.MethodGet, uri, testCase{
headers: map[string]string{
requestHeaders: map[string]string{
"Authorization": fmt.Sprintf("%s %s", prefix, token),
},
}).Reply(fasthttp.StatusOK)
Expand All @@ -800,7 +801,7 @@ func TestModifyRequest(t *testing.T) {

// Set up a mock matcher
mock := NewMock(fasthttp.MethodGet, uri, testCase{
headers: map[string]string{
requestHeaders: map[string]string{
"X-TEST": "test",
},
}).Reply(fasthttp.StatusOK)
Expand Down Expand Up @@ -1147,7 +1148,7 @@ func TestTable(t *testing.T) {
},
New(fasthttp.MethodGet, joinURI(httpEndpoint, "simple_headers")): {
expectedStatusCode: fasthttp.StatusOK,
headers: map[string]string{
requestHeaders: map[string]string{
"X-TEST-HEADER-1": "sExavefMTeOVFu6LfLLN",
"X-TEST-HEADER-2": "zHW4aaMhMJzrA5eJtahB 你好世界 😊😎",
},
Expand Down Expand Up @@ -1216,6 +1217,12 @@ func TestTable(t *testing.T) {
responseBody: []byte("no authorization"),
expectedError: "401 Unauthorized [body=no authorization]",
},
New(fasthttp.MethodGet, joinURI(httpEndpoint, "422_response_withRFC9457")).AcceptedResponseCodes([]int{fasthttp.StatusNoContent}): {
expectedStatusCode: fasthttp.StatusUnprocessableEntity,
responseHeaders: map[string]string{"Content-Type": "application/problem+json"},
responseBody: []byte(`{"$schema":"http://localhost:8145/schemas/ErrorModel.json","title":"Unprocessable Entity","status":422,"detail":"validation failed","errors":[{"message":"expected object","location":"body.commonAnnotations"}]}]}`),
expectedError: `422 Unprocessable Entity [body={"$schema":"http://localhost:8145/schemas/ErrorModel.json","title":"Unprocessable Entity","status":422,"detail":"validation failed","errors":[{"message":"expected object","location":"body.commonAnnotations"}]}]}]`,
},
}

for k, v := range testRequests {
Expand Down Expand Up @@ -1257,8 +1264,8 @@ func runGenericRequest(k *Request, v testCase) error {
}

// Handle headers
if len(v.headers) > 0 {
req.Headers(v.headers)
if len(v.requestHeaders) > 0 {
req.Headers(v.requestHeaders)
}

// Handle request body
Expand Down
12 changes: 6 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@ go 1.22.5

require (
github.com/json-iterator/go v1.1.12
github.com/valyala/fasthttp v1.55.0
golang.org/x/net v0.28.0
github.com/valyala/fasthttp v1.56.0
golang.org/x/net v0.30.0
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/rogpeppe/go-internal v1.12.0 // indirect
github.com/rogpeppe/go-internal v1.13.1 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
Expand Down
25 changes: 14 additions & 11 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,41 +1,44 @@
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.55.0 h1:Zkefzgt6a7+bVKHnu/YaYSOPfNYNisSVBo/unVCf8k8=
github.com/valyala/fasthttp v1.55.0/go.mod h1:NkY9JtkrpPKmgwV3HTaS2HWaJss9RSIsRVfcxxoHiOM=
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
github.com/valyala/fasthttp v1.56.0 h1:bEZdJev/6LCBlpdORfrLu/WOZXXxvrUQSiyniuaoW8U=
github.com/valyala/fasthttp v1.56.0/go.mod h1:sReBt3XZVnudxuLOx4J/fMrJVorWRiWY2koQKgABiVI=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
Expand Down
9 changes: 5 additions & 4 deletions mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func NewMock(method, uri string, t testCase, matchFns ...MockMatchFn) *Mock {
panic(err)
}
if !caCertPool.AppendCertsFromPEM([]byte(testCACert)) {
panic(err)
panic("failed to append mock server CA certificate")
}

m.ln = tls.NewListener(m.ln, &tls.Config{
Expand All @@ -122,6 +122,7 @@ func NewMock(method, uri string, t testCase, matchFns ...MockMatchFn) *Mock {
MinVersion: tls.VersionTLS12,
}
}
m.RespHeaders(t.responseHeaders)

m.handler = func(ctx *fasthttp.RequestCtx) {

Expand Down Expand Up @@ -167,10 +168,10 @@ func NewMock(method, uri string, t testCase, matchFns ...MockMatchFn) *Mock {
}

// Handle headers
if len(t.headers) > 0 {
for key, val := range t.headers {
if len(t.requestHeaders) > 0 {
for key, val := range t.requestHeaders {
if string(ctx.Request.Header.Peek(key)) != val {
ctx.Error(fmt.Sprintf("MOCK: non-matching header (want %v, have %v)", t.headers, string(ctx.Request.Header.Peek(key))), fasthttp.StatusInternalServerError)
ctx.Error(fmt.Sprintf("MOCK: non-matching header (want %v, have %v)", t.requestHeaders, string(ctx.Request.Header.Peek(key))), fasthttp.StatusInternalServerError)
return
}
}
Expand Down
8 changes: 4 additions & 4 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
// Identical to struct used in labstack/echo
type HTTPError struct {
Code int
Message interface{}
Message any
Internal error // Stores the error returned by an external dependency
}

Expand All @@ -34,21 +34,21 @@ func Copy(w io.Writer) func(resp *fasthttp.Response) error {
}

// ParseJSON parses the response body as JSON into a struct
func ParseJSON(v interface{}) func(resp *fasthttp.Response) error {
func ParseJSON(v any) func(resp *fasthttp.Response) error {
return func(resp *fasthttp.Response) error {
return jsoniter.Unmarshal(resp.Body(), v)
}
}

// ParseYAML parses the response body as YAML into a struct
func ParseYAML(v interface{}) func(resp *fasthttp.Response) error {
func ParseYAML(v any) func(resp *fasthttp.Response) error {
return func(resp *fasthttp.Response) error {
return yaml.Unmarshal(resp.Body(), v)
}
}

// ParseXML parses the response body as XML into a struct
func ParseXML(v interface{}) func(resp *fasthttp.Response) error {
func ParseXML(v any) func(resp *fasthttp.Response) error {
return func(resp *fasthttp.Response) error {
return xml.Unmarshal(resp.Body(), v)
}
Expand Down
2 changes: 0 additions & 2 deletions tls.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import (
"path/filepath"
)

// var defaultTransport = http.DefaultTransport.(*http.Transport).Clone()

// setupClientCertificateFromBytes reads the provided client certificate / key and CA certificate
// from memory and creates / modifies a tls.Config object
func setupClientCertificateFromBytes(clientCert, clientKey, caCert []byte, tlsConfig *tls.Config) (*tls.Config, error) {
Expand Down
Loading