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

オープン
#28 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

@team-humaki がすでに取り組んでいます。

2026年9月16日 から。

  • #67 @team-humaki による — オープン

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
50/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
停滞
技術スタック
go
領域
api, backend

調査の方向性

JSON がリクエストコンテキストにアクセスする responder.go の 103 行目から始め、issue に示されている wrapper test で失敗を再現します。nil-request パスを確認し、要求されたステータスの動作を維持したまま、panic なしでレスポンスボディが書き込まれることを検証します。

索引モデルが issue の本文から書いたものです。

説明

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?

主要言語
Go
スター
340
フォーク
69
PR マージ指標
30日以内にマージされた PR はありません

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

go-chi/render のほかの issue

go-chi/render の issue をすべて見る

似ている issue

Go の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。