Skip to content

Commit 827b70e

Browse files
authored
static: handle If-None-Match for ETag. (#200)
1 parent addc746 commit 827b70e

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

static.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -178,8 +178,12 @@ func staticHandler(ctx *Context, log *log.Logger, opt StaticOptions) bool {
178178
}
179179

180180
if opt.ETag {
181-
tag := GenerateETag(string(fi.Size()), fi.Name(), fi.ModTime().UTC().Format(http.TimeFormat))
182-
ctx.Resp.Header().Set("ETag", `"`+tag+`"`)
181+
tag := `"` + GenerateETag(string(fi.Size()), fi.Name(), fi.ModTime().UTC().Format(http.TimeFormat)) + `"`
182+
ctx.Resp.Header().Set("ETag", tag)
183+
if ctx.Req.Header.Get("If-None-Match") == tag {
184+
ctx.Resp.WriteHeader(http.StatusNotModified)
185+
return true
186+
}
183187
}
184188

185189
http.ServeContent(ctx.Resp, ctx.Req.Request, file, fi.ModTime(), f)

static_test.go

+22-4
Original file line numberDiff line numberDiff line change
@@ -176,8 +176,7 @@ func Test_Static_Options(t *testing.T) {
176176
})
177177

178178
Convey("Serve static files with options expires", t, func() {
179-
var buf bytes.Buffer
180-
m := NewWithLogger(&buf)
179+
m := New()
181180
opt := StaticOptions{Expires: func() string { return "46" }}
182181
m.Use(Static(currentRoot, opt))
183182

@@ -190,8 +189,7 @@ func Test_Static_Options(t *testing.T) {
190189
})
191190

192191
Convey("Serve static files with options ETag", t, func() {
193-
var buf bytes.Buffer
194-
m := NewWithLogger(&buf)
192+
m := New()
195193
opt := StaticOptions{ETag: true}
196194
m.Use(Static(currentRoot, opt))
197195

@@ -203,6 +201,26 @@ func Test_Static_Options(t *testing.T) {
203201

204202
So(resp.Header().Get("ETag"), ShouldEqual, `"`+tag+`"`)
205203
})
204+
205+
Convey("Serve static files with ETag in If-None-Match", t, func() {
206+
m := New()
207+
opt := StaticOptions{ETag: true}
208+
m.Use(Static(currentRoot, opt))
209+
210+
resp := httptest.NewRecorder()
211+
req, err := http.NewRequest("GET", "http://localhost:4000/macaron.go", nil)
212+
So(err, ShouldBeNil)
213+
m.ServeHTTP(resp, req)
214+
tag := GenerateETag(string(resp.Body.Len()), "macaron.go", resp.Header().Get("last-modified"))
215+
216+
// Second request with ETag in If-None-Match
217+
resp = httptest.NewRecorder()
218+
req.Header.Add("If-None-Match", `"`+tag+`"`)
219+
m.ServeHTTP(resp, req)
220+
221+
So(resp.Code, ShouldEqual, http.StatusNotModified)
222+
So(len(resp.Body.Bytes()), ShouldEqual, 0)
223+
})
206224
}
207225

208226
func Test_Static_Redirect(t *testing.T) {

0 commit comments

Comments
 (0)