-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
97 lines (89 loc) · 2.37 KB
/
main.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"strings"
)
var envListen = stringResolve("LISTEN_ADDR", ":8080")
var envIqdbAddr = stringResolve("IQDB_ADDR", "iqdb:5566")
var envServiceName = stringResolve("SERVICE_NAME", "iibooru")
var envTreshold = stringResolve("MATCH_TRESHOLD", "60")
var splitter *regexp.Regexp
func init() {
splitter, _ = regexp.Compile("\\s+")
}
func stringResolve(name, def string) string {
if v, ok := os.LookupEnv(name); ok {
return v
}
return def
}
func iqdbHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(1024 * 1024 * 100)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error()))
return
}
var bss []byte
h, ok := r.MultipartForm.File["file"]
if !ok || len(h) != 1 {
if url, ok := r.MultipartForm.Value["url"]; !ok || len(url) != 1 {
w.WriteHeader(http.StatusInternalServerError)
return
} else {
resp, err := http.Get(url[0])
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error()))
return
}
bs, err := ioutil.ReadAll(resp.Body)
defer func() {
_ = resp.Body.Close()
}()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error()))
return
}
bss = bs
}
} else {
f, err := h[0].Open()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error()))
return
}
bs, err := ioutil.ReadAll(f)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error()))
return
}
bss = bs
}
res, err := QueryData(envIqdbAddr, "0", 0, 10, bss)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error()))
return
}
matches := &strings.Builder{}
for _, r := range res {
matches.Write([]byte(fmt.Sprintf(" <match id='%d' service='%s' sim='%f' width='%d' height='%d'><image id='%d'/></match>\n", r.ImgId, envServiceName, r.Score, r.Width, r.Height, r.ImgId)))
}
w.Header().Set("content-type", "application/xml; charset=utf-8")
_, _ = w.Write([]byte(fmt.Sprintf("<?xml version='1.0' encoding='UTF-8'?>\n<matches threshold='%s'>\n%s</matches>", envTreshold, matches)))
}
func main() {
http.HandleFunc("/iqdb", iqdbHandler)
err := http.ListenAndServe(envListen, nil)
if err != nil {
panic(err)
}
}