How to send 204 No content with Go http package?

I built a tiny sample application with Go on Google App Engine that sends string responses when calling different URLs. But how can I use the Go http packet to send a 204 No Content response to clients?

package hello import ( "fmt" "net/http" "appengine" "appengine/memcache" ) func init() { http.HandleFunc("/", hello) http.HandleFunc("/hits", showHits) } func hello(w http.ResponseWriter, r *http.Request) { name := r.Header.Get("name") fmt.Fprintf(w, "Hello %s!", name) } func showHits(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "%d", hits(r)) } func hits(r *http.Request) uint64 { c := appengine.NewContext(r) newValue, _ := memcache.Increment(c, "hits", 1, 0) return newValue } 
+4
source share
2 answers

According to the package documents:

 func NoContent(w http.ResponseWriter, r *http.Request) { // Set up any headers you want here. w.WriteHeader(204) // send the headers with a 204 response code. } 

will send the client a status of 204.

+10
source

Sending 204 responses from your script means that your instance still needs to be launched and costs you money. If you are looking for a caching solution. Google got it and called Edge Cache.

You only need to answer with the following headers, and Google will automatically cache your response on several servers closest to the users (i.e. respond with 204). This will significantly increase the speed of your site and reduce the cost of the instance.

 w.Header().Set("Cache-Control", "public, max-age=86400") w.Header().Set("Pragma", "Public") 

You can set the maximum age, but do it wisely.

By the way, it seems that billing should be enabled to use the edge cache

+2
source

Source: https://habr.com/ru/post/1492623/


All Articles