2018-04-29 19:35:04 -04:00
|
|
|
// Copyright 2018 Frédéric Guillot. All rights reserved.
|
|
|
|
// Use of this source code is governed by the Apache 2.0
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2018-08-25 00:51:50 -04:00
|
|
|
package response // import "miniflux.app/http/response"
|
2018-04-29 19:35:04 -04:00
|
|
|
|
|
|
|
import (
|
2018-07-06 23:39:28 -04:00
|
|
|
"compress/flate"
|
|
|
|
"compress/gzip"
|
2018-04-29 19:35:04 -04:00
|
|
|
"net/http"
|
2018-07-06 23:39:28 -04:00
|
|
|
"strings"
|
2018-04-29 19:35:04 -04:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Redirect redirects the user to another location.
|
|
|
|
func Redirect(w http.ResponseWriter, r *http.Request, path string) {
|
|
|
|
http.Redirect(w, r, path, http.StatusFound)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NotModified sends a response with a 304 status code.
|
|
|
|
func NotModified(w http.ResponseWriter) {
|
|
|
|
w.WriteHeader(http.StatusNotModified)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cache returns a response with caching headers.
|
2018-07-19 22:27:05 -04:00
|
|
|
func Cache(w http.ResponseWriter, r *http.Request, mimeType, etag string, data []byte, duration time.Duration) {
|
2018-04-29 19:35:04 -04:00
|
|
|
w.Header().Set("Content-Type", mimeType)
|
|
|
|
w.Header().Set("ETag", etag)
|
|
|
|
w.Header().Set("Cache-Control", "public")
|
|
|
|
w.Header().Set("Expires", time.Now().Add(duration).Format(time.RFC1123))
|
|
|
|
|
|
|
|
if etag == r.Header.Get("If-None-Match") {
|
|
|
|
w.WriteHeader(http.StatusNotModified)
|
2018-07-19 22:27:05 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
switch mimeType {
|
|
|
|
case "text/javascript; charset=utf-8", "text/css; charset=utf-8":
|
|
|
|
Compress(w, r, data)
|
|
|
|
default:
|
|
|
|
w.Write(data)
|
2018-04-29 19:35:04 -04:00
|
|
|
}
|
|
|
|
}
|
2018-07-06 23:39:28 -04:00
|
|
|
|
|
|
|
// Compress the response sent to the browser.
|
|
|
|
func Compress(w http.ResponseWriter, r *http.Request, data []byte) {
|
|
|
|
acceptEncoding := r.Header.Get("Accept-Encoding")
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case strings.Contains(acceptEncoding, "gzip"):
|
|
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
|
|
gzipWriter := gzip.NewWriter(w)
|
|
|
|
defer gzipWriter.Close()
|
|
|
|
gzipWriter.Write(data)
|
|
|
|
case strings.Contains(acceptEncoding, "deflate"):
|
|
|
|
w.Header().Set("Content-Encoding", "deflate")
|
|
|
|
flateWriter, _ := flate.NewWriter(w, -1)
|
|
|
|
defer flateWriter.Close()
|
|
|
|
flateWriter.Write(data)
|
|
|
|
default:
|
|
|
|
w.Write(data)
|
|
|
|
}
|
|
|
|
}
|