-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
93 lines (79 loc) · 1.55 KB
/
request.go
File metadata and controls
93 lines (79 loc) · 1.55 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"errors"
"net/http"
"strconv"
"strings"
)
const (
SizeSmall = iota
SizeMedium
sizeBig
)
type Request struct {
lod int
file string
size int
format string
}
func parseReqUrl(url string) (Request, error) {
var r Request
if lod12Regex.MatchString(url) {
groups := lod12Regex.FindStringSubmatch(url)
//LOD
lod, err := strconv.ParseInt(groups[1], 10, 32)
r.lod = int(lod)
if err != nil {
return r, err
}
//file
r.file = groups[2]
//format
r.format = groups[3]
} else if lod3Regex.MatchString(url) {
groups := lod3Regex.FindStringSubmatch(url)
//LOD
r.lod = 3
//size
switch groups[1] {
case "small":
r.size = SizeSmall
case "medium":
r.size = SizeMedium
case "big":
r.size = sizeBig
default:
return r, errors.New("Unvalid size:" + groups[2])
}
//file
r.file = groups[2]
//format
r.format = groups[3]
}
return r, nil
}
func rewriteUrlWithWebp(url string, header http.Header) string {
strSplit := strings.Split(url, ".")
ext := strSplit[len(strSplit)-1]
if acceptsWebp(ext, header) {
strSplit[len(strSplit)-1] = "webp"
return strings.Join(strSplit, ".")
} else {
strSplit[len(strSplit)-1] = "jpg"
return strings.Join(strSplit, ".")
}
}
func acceptsWebp(ext string, header http.Header) bool {
suffixes := []string{"jpg", "jpeg", "JPG", "JPEG"}
for _, s := range suffixes {
if ext == s {
for _, subElem := range strings.Split(header.Get("Accept"), ",") {
if subElem == "image/webp" {
return true
}
}
return false
}
}
return true
}