-
Notifications
You must be signed in to change notification settings - Fork 2
/
37-thumbnail.go
59 lines (50 loc) · 1.29 KB
/
37-thumbnail.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
package main
import (
"github.com/disintegration/imaging"
"io"
"log"
"net/http"
"strconv"
)
type ImageFetchResult struct {
Error error
Reader io.Reader
}
func fetchImage(url string, channel chan ImageFetchResult) {
res, err := http.Get(url)
if err != nil {
log.Println(err)
channel <- ImageFetchResult{Error: err}
return
}
channel <- ImageFetchResult{Reader: res.Body}
}
func index(w http.ResponseWriter, r *http.Request) {
imageUrl := r.URL.Query().Get("url")
imageWidth := r.URL.Query().Get("width")
imageHeight := r.URL.Query().Get("height")
if imageUrl == "" || imageWidth == "" || imageHeight == "" {
http.Error(w, "Requisição inválida", http.StatusBadRequest)
return
}
channel := make(chan ImageFetchResult)
go fetchImage(imageUrl, channel)
result := <-channel
if result.Error != nil {
http.Error(w, "Requisição inválida", http.StatusBadRequest)
return
}
img, err := imaging.Decode(result.Reader)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
widthFinal, _ := strconv.Atoi(imageWidth)
heightFinal, _ := strconv.Atoi(imageHeight)
thumb := imaging.Thumbnail(img, widthFinal, heightFinal, imaging.CatmullRom)
imaging.Encode(w, thumb, imaging.JPEG)
}
func main() {
http.HandleFunc("/", index)
http.ListenAndServe(":8080", nil)
}