-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
client_hints_handler.go
62 lines (46 loc) · 1.38 KB
/
client_hints_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2017 Axel Etcheverry. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package middlewares
import (
"fmt"
"math"
"net/http"
"strconv"
)
func parseInt(value string) int {
return int(math.Floor(parseFloat(value) + 0.5))
}
func parseFloat(value string) float64 {
val, _ := strconv.ParseFloat(value, 64)
return math.Abs(val)
}
// NewClientHintsHandler parse query string
// see: http://httpwg.org/http-extensions/client-hints.html
func NewClientHintsHandler() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
options, err := OptionsFromContext(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if dpr := r.Header.Get("DPR"); dpr != "" {
options.DPR = parseFloat(dpr)
w.Header().Set("Content-DPR", fmt.Sprintf("%.1f", options.DPR))
w.Header().Add("Vary", "DPR")
}
if width := r.Header.Get("Width"); width != "" {
options.Width = parseInt(width)
w.Header().Add("Vary", "Width")
}
if saveData := r.Header.Get("Save-Data"); saveData == "on" {
options.Quality = 65
w.Header().Add("Vary", "Save-Data")
}
r = r.WithContext(NewOptionsContext(ctx, options))
next.ServeHTTP(w, r)
})
}
}