Skip to content

Commit

Permalink
[patch] fix infinite recursion on structured response failure
Browse files Browse the repository at this point in the history
  • Loading branch information
bnkamalesh committed Apr 21, 2024
1 parent cc2bb0c commit cbb3fb9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 14 deletions.
34 changes: 20 additions & 14 deletions responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import (
"net/http"
)

var (
jsonErrPayload = []byte{}
)

// ErrorData used to render the error page
type ErrorData struct {
ErrCode int
Expand Down Expand Up @@ -69,29 +73,31 @@ func SendResponse(w http.ResponseWriter, data interface{}, rCode int) {
w = crwAsserter(w, rCode)
w.Header().Add(HeaderContentType, JSONContentType)
err := json.NewEncoder(w).Encode(dOutput{Data: data, Status: rCode})
if err != nil {
/*
In case of encoding error, send "internal server error" and
log the actual error.
*/
R500(w, ErrInternalServer)
LOGHANDLER.Error(err)
if err == nil {
return
}

// assuming the error was related to JSON encoding, so reattempting to respond
// with a static payload. This could still fail in case of network write or other error(s)
w = crwAsserter(w, http.StatusInternalServerError)
_, _ = w.Write(jsonErrPayload)
LOGHANDLER.Error(err)
}

// SendError is used to respond to any request with an error
func SendError(w http.ResponseWriter, data interface{}, rCode int) {
w = crwAsserter(w, rCode)
w.Header().Add(HeaderContentType, JSONContentType)
err := json.NewEncoder(w).Encode(errOutput{data, rCode})
if err != nil {
/*
In case of encoding error, send "internal server error" and
log the actual error.
*/
R500(w, ErrInternalServer)
LOGHANDLER.Error(err)
if err == nil {
return
}

// assuming the error was related to JSON encoding, so reattempting to respond
// with a static payload. This could still fail in case of network write or other error(s)
w = crwAsserter(w, http.StatusInternalServerError)
_, _ = w.Write(jsonErrPayload)
LOGHANDLER.Error(err)
}

// Render is used for rendering templates (HTML)
Expand Down
10 changes: 10 additions & 0 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package webgo
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
Expand All @@ -21,6 +22,15 @@ type httpResponseWriter interface {
}

func init() {
var err error
jsonErrPayload, err = json.Marshal(errOutput{
Errors: ErrInternalServer,
Status: http.StatusInternalServerError,
})
if err != nil {
panic(err)
}

// ensure the custom response writer implements all the required functions
crw := &customResponseWriter{}
_ = httpResponseWriter(crw)
Expand Down

0 comments on commit cbb3fb9

Please sign in to comment.