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
|
package main
import (
"bytes"
"io"
"log"
"mime/multipart"
"net/http"
"os/exec"
"strconv"
"strings"
)
const (
B uint64 = 1
KB uint64 = 1 << (10 * iota)
MB
GB
TB
PB
EB
)
const maxSize = 24 * KB
func main() {
log.Printf("Start gif2web server on 8080")
http.Handle("/convert", gifProcessor())
http.ListenAndServe("0.0.0.0:8080", nil)
}
func gifProcessor() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if err := req.ParseMultipartForm(maxSize); nil != err {
log.Printf("Error while parse: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
for _, fheaders := range req.MultipartForm.File {
for _, hdr := range fheaders {
log.Printf("Income file len: %d", hdr.Size)
var err error
var infile multipart.File
if infile, err = hdr.Open(); err != nil {
log.Printf("[ERROR] Handle open error: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
quality := req.URL.Query().Get("quality")
if quality == "" {
quality = "0"
}
q, err := strconv.ParseInt(quality, 10, 64)
if err != nil || q < 0 || q > 100 {
log.Printf("[ERROR] Bad quality params: %s %v", err, q)
w.WriteHeader(http.StatusInternalServerError)
return
}
cmd := exec.Command("gif2webp", "-mixed", "-q", strconv.Itoa(int(q)), "-o", "-", "--", "-")
cmd.Stdin = io.Reader(infile)
var out bytes.Buffer
cmd.Stdout = &out
var errout bytes.Buffer
cmd.Stderr = &errout
err = cmd.Run()
if err != nil {
log.Printf("[ERROR] Webp Output: %v, %v, %v\n", err, out.String(), errout.String())
w.WriteHeader(http.StatusInternalServerError)
return
}
output := out.String()
reader := strings.NewReader(output)
imageLen := reader.Len()
log.Printf("Outcome file len: %d", reader.Len())
w.Header().Set("Content-Type", "image/webp")
w.Header().Set("Content-Length", strconv.Itoa(imageLen))
w.WriteHeader(http.StatusOK)
io.Copy(w, reader)
return
}
}
w.WriteHeader(http.StatusInternalServerError)
})
}
|