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

Using render.JSON with no http Request object throws an error #28

Open
o-aloqaily opened this issue Dec 1, 2020 · 0 comments
Open

Using render.JSON with no http Request object throws an error #28

o-aloqaily opened this issue Dec 1, 2020 · 0 comments

Comments

@o-aloqaily
Copy link

In the responder, render.JSON() function takes in an "http.Request" object which will be used to get the http response status code

I'm customizing the behavior of the function, by wrapping it with a wrapper function in my project. So I can call one function to pass in the response body as well as the status code, like so

func (r *responder) JSON(w http.ResponseWriter, v interface{}, s int) {
	// Write http response status
	w.WriteHeader(s)
	render.JSON(w, nil, v)
}

When "nil" is passed is shown above instead of an http.Request object, the function throws an error.

--- FAIL: TestJSON (0.00s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
	panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0xf0 pc=0x12a9ca0]

Here is the test I wrote to test the wrapper:

func TestJSON(t *testing.T) {
	type mockResponse struct {
		MockField string `json:"field"`
	}
	responder := NewResponder()

	recorder := httptest.NewRecorder()
	responder.JSON(recorder, mockResponse{MockField: "test"}, http.StatusOK)
	assert.Equal(t, recorder.Code, 200)
	assert.JSONEq(t, `{"field": "test"}`, recorder.Body.String())
}

I did some debugging, it seems like the error is caused by line 103 in JSON function in responder.go, which is the following:

	if status, ok := r.Context().Value(StatusCtxKey).(int); ok {
		w.WriteHeader(status)
	}

How about adding a check for when the request object is nil, it skips this whole check and only writes the body to the buffer?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant