forked from yano3/oyaki
-
Notifications
You must be signed in to change notification settings - Fork 1
/
webp.go
61 lines (56 loc) · 1.34 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
package main
import (
"bytes"
"fmt"
"github.com/h2non/bimg"
"io"
"log"
"net/http"
"net/url"
)
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, quality int) (*bytes.Buffer, error) {
out, err := io.ReadAll(src)
if err != nil {
return nil, err
}
opts := bimg.Options{
Type: bimg.WEBP,
Quality: quality,
NoAutoRotate: false,
// NoAutoRotateはデフォルトでfalseで、勝手にrotateしてくれる
}
webpImg, err := bimg.NewImage(out).Process(opts)
if err != nil {
return nil, err
}
return bytes.NewBuffer(webpImg), nil
}