forked from yano3/oyaki
-
Notifications
You must be signed in to change notification settings - Fork 1
/
webp.go
71 lines (63 loc) · 1.52 KB
/
webp.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
63
64
65
66
67
68
69
70
71
package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"github.com/disintegration/imaging"
)
func doWebp(req *http.Request) (*http.Response, error) {
var orgRes *http.Response
orgURL := req.URL
newPath := orgURL.Path[:len(orgURL.Path)-len(".webp")]
newOrgURL, err := url.Parse(fmt.Sprintf("%s://%s%s?%s", orgURL.Scheme, orgURL.Host, newPath, orgURL.RawQuery))
if err != nil {
log.Println(err)
return nil, err
}
newReq, err := http.NewRequest("GET", newOrgURL.String(), nil)
newReq.Header = req.Header
if err != nil {
log.Println(err)
return nil, err
}
orgRes, err = client.Do(newReq)
if err != nil {
log.Println(err)
return nil, err
}
if orgRes.StatusCode != 200 && orgRes.StatusCode != 304 {
log.Println(orgRes.Status)
return nil, fmt.Errorf("origin response is not 200 or 304")
}
if orgRes == nil {
return nil, fmt.Errorf("origin response is not found")
}
return orgRes, nil
}
func convWebp(src io.Reader, params []string) (*bytes.Buffer, error) {
f, err := os.CreateTemp("/tmp", "")
if err != nil {
return nil, err
}
defer f.Close()
defer os.Remove(f.Name())
img, err := imaging.Decode(src, imaging.AutoOrientation(true))
if err != nil {
return nil, err
}
if err := imaging.Encode(f, img, imaging.JPEG); err != nil {
return nil, err
}
params = append(params, "-quiet", "-mt", "-jpeg_like", f.Name(), "-o", "-")
out, err := exec.Command("cwebp", params...).Output()
if err != nil {
log.Println(err)
return nil, err
}
return bytes.NewBuffer(out), nil
}