-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
wallpaper.go
98 lines (81 loc) · 2 KB
/
wallpaper.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
package handler
import (
"math/rand"
"net/http"
"strconv"
bing_wallpaper "github.com/TimothyYe/bing-wallpaper"
"github.com/gin-gonic/gin"
)
const (
random = "random"
)
var (
marketMap = map[int]string{
0: "zh-CN",
1: "en-US",
2: "ja-JP",
3: "en-AU",
4: "en-GB",
5: "de-DE",
6: "en-NZ",
7: "en-CA",
8: "en-IN",
}
)
func getRandomIndex() int {
min := 0
max := 8
return rand.Intn(max-min+1) + min
}
func getRandomMarket() string {
return marketMap[getRandomIndex()]
}
// RootHandler handles default API requests
func RootHandler(c *gin.Context) {
resolution := c.DefaultQuery("resolution", "1920")
format := c.DefaultQuery("format", "json")
imageFormat := c.DefaultQuery("image_format", "jpg")
index := c.DefaultQuery("index", "0")
mkt := c.DefaultQuery("mkt", "zh-CN")
// handle the random index
if index == random {
index = strconv.Itoa(getRandomIndex())
}
// handle the random market parameter
if mkt == random {
mkt = getRandomMarket()
}
// check index
uIndex, err := strconv.ParseUint(index, 10, 64)
if err != nil {
// input index is invalid
c.String(http.StatusInternalServerError, "the image index is invalid")
return
}
// check format
if format != "json" && format != "image" {
c.String(http.StatusInternalServerError, "format parameter is invalid, should be json or image")
return
}
if imageFormat != "jpg" && imageFormat != "webp" {
c.String(http.StatusInternalServerError, "image_format parameter is invalid, should be jpg or webp")
return
}
// fetch bing information
response, err := bing_wallpaper.Get(uint(uIndex), mkt, resolution)
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
// check the image format
if imageFormat == "webp" {
response.URL = response.URL[:len(response.URL)-3] + "webp"
}
// redirect to image URL directly
if format == "image" && response.URL != "" {
c.Redirect(http.StatusTemporaryRedirect, response.URL)
return
}
// render response as JSON
c.JSON(http.StatusOK, response)
}