]> Sergey Matveev's repositories - tofuproxy.git/blob - rounds/40transcodeWebP.go
Refactoring
[tofuproxy.git] / rounds / 40transcodeWebP.go
1 /*
2 tofuproxy -- HTTP proxy with TLS certificates management
3 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package rounds
19
20 import (
21         "fmt"
22         "io"
23         "io/ioutil"
24         "log"
25         "net/http"
26         "os"
27         "os/exec"
28
29         "go.stargrave.org/tofuproxy/fifos"
30 )
31
32 const CmdDWebP = "dwebp"
33
34 func RoundTranscodeWebP(
35         host string,
36         resp *http.Response,
37         w http.ResponseWriter,
38         req *http.Request,
39 ) (bool, error) {
40         if resp.Header.Get("Content-Type") != "image/webp" || isXombrero(req) {
41                 return true, nil
42         }
43         tmpFd, err := ioutil.TempFile("", "tofuproxy.*.webp")
44         if err != nil {
45                 log.Fatalln(err)
46         }
47         defer os.Remove(tmpFd.Name())
48         defer tmpFd.Close()
49         defer resp.Body.Close()
50         if _, err = io.Copy(tmpFd, resp.Body); err != nil {
51                 log.Printf("Error during %s: %+v\n", req.URL, err)
52                 return false, err
53         }
54         tmpFd.Close()
55         cmd := exec.Command(CmdDWebP, tmpFd.Name(), "-o", "-")
56         data, err := cmd.Output()
57         if err != nil {
58                 return false, err
59         }
60         w.Header().Add("Content-Type", "image/png")
61         w.WriteHeader(http.StatusOK)
62         w.Write(data)
63         fifos.SinkOther <- fmt.Sprintf(
64                 "%s %s\t%d\tWebP transcoded to PNG",
65                 req.Method,
66                 req.URL.String(),
67                 http.StatusOK,
68         )
69         return false, nil
70 }