Skip to content

Commit 7b00ea3

Browse files
committed
fix: 修正 NotModified 无法正确返回 content-type 的问题
1 parent c453ef6 commit 7b00ea3

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

output.go

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,8 @@ func (ctx *Context) SetCookies(c ...*http.Cookie) {
179179
// func()(body any, err error)
180180
//
181181
// 如果返回 body 的是 []byte 类型,会原样输出,其它类型则按照 [Context.Marshal] 进行转换成 []byte 之后输出。
182+
// body 可能参与了 etag 的计算,为了防止重复生成 body,所以此函数允许 body 直接为 []byte 类型,
183+
// 在不需要 body 参与计算 etag 的情况下,应该返回非 []byte 类型的 body。
182184
func NotModified(etag func() (string, bool), body func() (any, error)) Responser {
183185
return ResponserFunc(func(ctx *Context) {
184186
if ctx.Request().Method == http.MethodGet {
@@ -194,19 +196,18 @@ func NotModified(etag func() (string, bool), body func() (any, error)) Responser
194196
return
195197
}
196198

197-
var data []byte
198-
if d, ok := b.([]byte); ok {
199-
data = d
200-
} else {
201-
if data, err = ctx.Marshal(b); err != nil {
202-
ctx.Error(err, ProblemNotAcceptable).Apply(ctx)
203-
return
199+
if data, ok := b.([]byte); ok {
200+
ctx.Header().Set(header.ContentType, qheader.BuildContentType(ctx.Mimetype(false), ctx.Charset()))
201+
if id := ctx.LanguageTag().String(); id != "" {
202+
ctx.Header().Set(header.ContentLanguage, id)
204203
}
205-
}
206204

207-
ctx.WriteHeader(http.StatusOK)
208-
if _, err := ctx.Write(data); err != nil {
209-
ctx.Logs().ERROR().Error(err)
205+
ctx.WriteHeader(http.StatusOK)
206+
if _, err := ctx.Write(data); err != nil {
207+
ctx.Logs().ERROR().Error(err)
208+
}
209+
} else {
210+
ctx.Render(http.StatusOK, b)
210211
}
211212
})
212213
}

output_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,8 @@ func TestNotModified(t *testing.T) {
249249
r := httptest.NewRequest(http.MethodGet, "/p", nil)
250250
s.NewContext(w, r, types.NewContext()).apply(nm)
251251
tag := w.Header().Get(header.ETag)
252-
a.Equal(w.Result().StatusCode, http.StatusOK).NotEmpty(tag)
252+
a.Equal(w.Result().StatusCode, http.StatusOK).NotEmpty(tag).
253+
Equal(w.Result().Header.Get("Content-Type"), "application/json; charset=utf-8")
253254

254255
w = httptest.NewRecorder()
255256
r = httptest.NewRequest(http.MethodGet, "/p", nil)

0 commit comments

Comments
 (0)