-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathworker.go
More file actions
92 lines (76 loc) · 1.71 KB
/
worker.go
File metadata and controls
92 lines (76 loc) · 1.71 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
package main
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"strconv"
)
var httpClient = http.DefaultClient
type Worker struct {
Id int
Query *Query
Cache *Cache
Processor *Processor
useCache bool
}
func NewWorker(id int) *Worker {
w := &Worker{
Id: id,
Query: NewQuery(),
Processor: NewProcessor(),
}
config := LoadConfig()
if config.Cache.Enable {
w.useCache = true
w.Cache = NewCache()
}
return w
}
func (worker *Worker) Execute(w http.ResponseWriter, r *http.Request) {
// parse query
if !worker.Query.Parse(r.URL.String()) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
var data []byte
var err error
var nocache bool
r.ParseForm()
if len(r.FormValue("nocache")) > 0 {
nocache = true
}
beCached := false
// ready image data
if worker.useCache && !nocache && worker.Cache.Exists(worker.Query) {
data, err = worker.Cache.Read(worker.Query)
} else {
response, err := httpClient.Get(worker.Query.SourceUrl)
if err == nil {
data, err = ioutil.ReadAll(response.Body)
}
defer response.Body.Close()
beCached = true
}
if err != nil {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
// image
src, err := NewImage(data)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
// process
dst := new(bytes.Buffer)
worker.Processor.Execute(src, dst, worker.Query)
// cache
if worker.useCache && beCached {
go worker.Cache.Write(worker.Query, dst.Bytes())
}
// response
w.Header().Set("Content-Type", http.DetectContentType(dst.Bytes()))
w.Header().Set("Content-Length", strconv.Itoa(dst.Len()))
io.Copy(w, dst)
}