-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutils.go
78 lines (69 loc) · 1.77 KB
/
utils.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
package main
import (
"crypto/md5"
"encoding/json"
"fmt"
"image"
"image/draw"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"github.com/nfnt/resize"
)
type Count struct {
Value int `json:"value"`
}
func cacheImages(digits *[]image.Image) {
cacheOneImage := func(no int) {
file, _ := os.Open(fmt.Sprintf("digits/%d.png", no))
defer file.Close()
(*digits)[no], _, _ = image.Decode(file)
}
for i := range *digits {
cacheOneImage(i) // to avoid resource leak
}
}
func generateMd5(id string) (string, error) {
w := md5.New()
if _, err := io.WriteString(w, id); err != nil {
return "", err
}
res := fmt.Sprintf("%x", w.Sum(nil))
return res, nil
}
func updateCounter(key string) string {
req, _ := http.NewRequest("GET", "https://api.countapi.xyz/hit/steins-gate-visitor-count/"+key, nil)
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ""
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ""
}
var count Count
if err = json.Unmarshal(body, &count); err != nil {
log.Println(err)
return ""
}
return strconv.Itoa(count.Value)
}
func generateImage(digits []image.Image, count string) image.Image {
length := len(count)
img := image.NewNRGBA(image.Rect(0, 0, 200*length, 200))
for i := range count {
index, _ := strconv.Atoi(count[i : i+1])
draw.Draw(img, image.Rect(i*200, 0, 200*length, 200), digits[index], digits[index].Bounds().Min, draw.Over)
}
return img
}
// resizeImage resize image to specified ratio
func resizeImage(img image.Image, ratio float64) image.Image {
width := uint(float64(img.Bounds().Max.X-img.Bounds().Min.X) * ratio)
height := uint(float64(img.Bounds().Max.Y-img.Bounds().Min.Y) * ratio)
return resize.Resize(width, height, img, resize.Lanczos3)
}