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

How to cache static files? #1222

Closed
zzwind opened this issue Jan 5, 2018 · 7 comments
Closed

How to cache static files? #1222

zzwind opened this issue Jan 5, 2018 · 7 comments

Comments

@zzwind
Copy link

zzwind commented Jan 5, 2018

Every static file http state code is 200
how to cache static files?
change satat code 200 to 304

@ghost
Copy link

ghost commented Jan 9, 2018

The status code 304 would not indicate a cached file but one was not modified.

But you are wrong. This is enough to enable HTTP Conditional Get:

r := gin.Default()
r.Static("/assets", "./assets")

A file in assets is returned including the HTTP header Last-Modified. The next request by the browser will send the corresponding If-Modified-Since header which Gin will respond to with 304 Not Modified.

@zzwind
Copy link
Author

zzwind commented Jan 22, 2018

@lutzhorn This is my code:

r := gin.Default()
r.Static("/assets", "web/public/")

But every refurbish browser,the css,js file will return 200 ( NOT from disk cache.)
How can i return 200 from disk cache.
Set http header can do this?

@yalay
Copy link

yalay commented Apr 26, 2019

+1

@appleboy
Copy link
Member

See the following example for gin Handler:

// ViewHandler support dist handler from UI
func ViewHandler() gin.HandlerFunc {
	fileServer := http.FileServer(dist.HTTP)
	data := []byte(time.Now().String())
	etag := fmt.Sprintf("%x", md5.Sum(data))

	return func(c *gin.Context) {
		c.Header("Cache-Control", "public, max-age=31536000")
		c.Header("ETag", etag)

		if match := c.GetHeader("If-None-Match"); match != "" {
			if strings.Contains(match, etag) {
				c.Status(http.StatusNotModified)
				return
			}
		}

		fileServer.ServeHTTP(c.Writer, c.Request)
	}
}

@zav8
Copy link

zav8 commented Jan 13, 2020

If you are using Chrome, maybe you should check if the "Disable cache" option is enabled.

Just with the simple r.Static(), 304 showed after I disabled this.

@liyishuai
Copy link

@appleboy's example is slightly inconsistent with HTTP standard.

	etag := fmt.Sprintf("%x", md5.Sum(data))

MD5 sum is a weak validator:

a validator is weak if it is shared by two or more representations of a given resource at the same time, unless those representations have identical representation data

Therefore, the ETag should be ("W/%x", md5.Sum(data)).

@vladtreny
Copy link

Hello,
Is it possible to disable Last-Modified header when using r.Static("/assets", "./assets") ?

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

6 participants