Add Expires headers Golang

I am struggling how to add caching to a website using Go. There are 2 main answers out there. Adding to robots.txt or to <head>.

<IfModule mod_expires.c>
  ExpiresActive on

# Your document html
  ExpiresByType text/html "access plus 0 seconds"

# Media: images, video, audio
  ExpiresByType image/jpeg "access plus 1 week"
  ExpiresByType image/png "access plus 1 week"
  ExpiresByType video/mp4 "access plus 1 week"

# CSS and JavaScript
  ExpiresByType application/javascript "access plus 1 week"
  ExpiresByType text/css "access plus 1 week"
</IfModule>

What I understand this is when you use Apache?

Or I have tried to add this in the header:

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5, minimum-scale=1 user-scalable=no">
    <link rel="stylesheet" type="text/css" href="css/layout.css">
    <script src="/js/accordion.js" defer></script> 
    Cache-Control: public, max-age=86400
  </head>

Here is the shortened code I use for “endpoints” and robots.txt. Google can read the robots.txt.

func index(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	path := strings.Trim(r.URL.Path, "/")

	switch path {
	case "robots.txt":
		http.ServeFile(w, r, "public/static/robots.txt")
	default:
		path = (path + ".html")
	}

}

How do I control caching when using Go?

I’ not sure I understand exactly your problem. However a Go web application don’t need an external web server (Apache,Nginex,etc). On the other hand managing cache on server side mean adding proper headers to the response writer, eg.

w.Header().Set("Cache-Control", "no-store, no-cache")

The goal is to cache the site for some days in order to speed up.

What is the syntax for doing this in html header? I assume it can be done in the template as well?

I am a bit confused. It seems to be 2 different headers and HTML5 does not use the caching in the html header. Can anybody confirm this?

Browser checks first response header for caching, if the response header doesn’t contain caching headers, it checks html tags. If the html doesn’t contain caching tags, browser uses default caching behaviour. From go side as @geosoft1 replied is enough for many browsers.

w.Header().Set(“Cache-Control”, “no-store, no-cache”)

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.