-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.go
101 lines (79 loc) · 2.05 KB
/
index.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
98
99
100
101
package handler
import (
"bytes"
"encoding/json"
"image"
"image/jpeg"
"image/png"
"io/ioutil"
"net/http"
"strconv"
"strings"
ui "image-to-ascii/ui"
"github.com/mattes/go-asciibot"
ascii "github.com/sophearak/goasciiart"
)
type asciiText struct {
ASCII string `json:"ascii"`
}
func asciirize(url string) []byte {
reqImg, err := http.Get(url)
if err != nil {
panic(err)
}
body, err := ioutil.ReadAll(reqImg.Body)
if err != nil {
panic(err)
}
img, _, _ := image.Decode(bytes.NewReader(body))
asciiBytes := ascii.Convert2Ascii(ascii.ScaleImage(img, 120))
reqImg.Body.Close()
return asciiBytes
}
func H(w http.ResponseWriter, r *http.Request) {
imgURL := r.URL.Query().Get("img")
o := r.URL.Query().Get("output")
ua := r.Header.Get("User-Agent")
if strings.Contains(ua, "curl") || strings.Contains(ua, "HTTPie") {
if len(imgURL) > 0 {
asciiBytes := asciirize(imgURL)
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Content-Length", strconv.Itoa(len(string(asciiBytes))))
w.Write(asciiBytes)
return
}
bot := asciibot.Random()
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Content-Length", strconv.Itoa(len(bot)))
w.Write([]byte(bot))
} else {
if len(imgURL) > 0 {
asciiBytes := asciirize(imgURL)
rgba, err := ascii.TextToImage(string(asciiBytes))
if err != nil {
panic(err)
}
buffer := new(bytes.Buffer)
switch o {
case "jpg":
jpeg.Encode(buffer, rgba, nil)
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
w.Write(buffer.Bytes())
case "png":
png.Encode(buffer, rgba)
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
w.Write(buffer.Bytes())
default:
r := asciiText{ASCII: string(asciiBytes)}
jm, _ := json.Marshal(r)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(string(jm))))
w.Write(jm)
}
} else {
ui.Index(w)
}
}
}