mirror of
https://github.com/labstack/echo.git
synced 2024-11-28 08:38:39 +02:00
fbb72869b3
* echo.context.cjson should encode the JSON before writing the status code #1334 : `response.Write` automatically sets status to `200` if a response code wasn't committed yet. This is convenient, but it ignores the fact that `response.Status` is a public field that may be set separately/before `response.Write` has been called A `response.Status` is by default `0`, or `200` if the response was reset, so `response.Write` should fallback to `200` only if a code wasn't set yet. * echo.context.cjson should encode the JSON before writing the status code #1334 : Writing the response code before encoding the payload is prone to error. If JSON encoding fails, the response code is already committed, the server is able to only modify the response body to reflect the error and the user receives an awkward response where the status is successful but the body reports an error. Instead - set the desired code on `c.response.Status`. If writing eventually takes place, the desired code is committed. If an error occurs, the server can still change the response.
44 lines
963 B
Go
44 lines
963 B
Go
package echo
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestResponse(t *testing.T) {
|
|
e := New()
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
rec := httptest.NewRecorder()
|
|
c := e.NewContext(req, rec)
|
|
res := &Response{echo: e, Writer: rec}
|
|
|
|
// Before
|
|
res.Before(func() {
|
|
c.Response().Header().Set(HeaderServer, "echo")
|
|
})
|
|
res.Write([]byte("test"))
|
|
assert.Equal(t, "echo", rec.Header().Get(HeaderServer))
|
|
}
|
|
|
|
func TestResponse_Write_FallsBackToDefaultStatus(t *testing.T) {
|
|
e := New()
|
|
rec := httptest.NewRecorder()
|
|
res := &Response{echo: e, Writer: rec}
|
|
|
|
res.Write([]byte("test"))
|
|
assert.Equal(t, http.StatusOK, rec.Code)
|
|
}
|
|
|
|
func TestResponse_Write_UsesSetResponseCode(t *testing.T) {
|
|
e := New()
|
|
rec := httptest.NewRecorder()
|
|
res := &Response{echo: e, Writer: rec}
|
|
|
|
res.Status = http.StatusBadRequest
|
|
res.Write([]byte("test"))
|
|
assert.Equal(t, http.StatusBadRequest, rec.Code)
|
|
}
|