http.Error put new line at the end of the response

1,631 views
Skip to first unread message

doom...@gmail.com

unread,
Jan 11, 2016, 12:03:23 PM1/11/16
to golang-nuts
Hi guys,

I've just started a project using plain http package from golang. I started from tests and got some strange behavior of http.Error() function. 

Below is a test case that I wrote. So, TestGetErr is failing and returning newline and spaces at the end of the response.

I'm pretty sure that I'm missing something, but can't realize what exactly.

Go: 1.5.2
OS: Win 10


package httperror_test
import (
"net/http"
"testing"
"net/http/httptest"
)

func getErr(resp http.ResponseWriter, req *http.Request) {
http.Error(resp, "Error", 500);
}

func getErrOk(resp http.ResponseWriter, req *http.Request) {
resp.Write([]byte("Error"))
}


func TestGetErr(t *testing.T) {
req, err := http.NewRequest("GET", "http://localhost", nil)
if err != nil {
t.Fatal(err)
}

w := httptest.NewRecorder()

getErr(w, req)
testResp(t, w)
}

func TestGetErrOk(t *testing.T) {
req, err := http.NewRequest("GET", "http://localhost", nil)
if err != nil {
t.Fatal(err)
}

w := httptest.NewRecorder()

getErrOk(w, req)
testResp(t, w);
}

func testResp(t *testing.T, w *httptest.ResponseRecorder) {
expectedBody := "Error"
if w.Body.String() != expectedBody {
t.Fatalf("\nExpected \n\t Body: '%s' but got '%s'", expectedBody, w.Body.String())
}
}



James Bardin

unread,
Jan 11, 2016, 12:56:13 PM1/11/16
to golang-nuts, doom...@gmail.com


On Monday, January 11, 2016 at 12:03:23 PM UTC-5, doom...@gmail.com wrote:
Hi guys,

I've just started a project using plain http package from golang. I started from tests and got some strange behavior of http.Error() function. 

Below is a test case that I wrote. So, TestGetErr is failing and returning newline and spaces at the end of the response.

 
Look at the http.Error function, and you'll see it calls fmt.Fprintln which adds a newline to the end https://golang.org/src/net/http/server.go?s=41562:41614#L1419

As for the spaces, there aren't any. Check the literal characters returned by the handler, or print the body with %q. 

doom...@gmail.com

unread,
Jan 11, 2016, 2:29:07 PM1/11/16
to golang-nuts, doom...@gmail.com
Thanks James, spaces were confusing me. I suppose that I got them because of Windows that needed \r to drop a cursor to the start of the line.
Reply all
Reply to author
Forward
0 new messages