-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (85 loc) · 2.02 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
98
99
100
101
102
103
104
105
106
107
package main
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"github.com/gin-gonic/gin"
_ "github.com/heroku/x/hmetrics/onload"
apixu "github.com/mohan3d/apixu-go"
)
var apiKey = os.Getenv("APIXU_KEY")
type weatherInfo struct {
TempC float64
TempF float64
Status string
Country string
Region string
ImageURL string
}
func getWeatherInfo(city string) (*weatherInfo, error) {
client := apixu.NewClient(apiKey)
currentWeather, err := client.Current(city)
if err != nil {
return nil, err
}
return &weatherInfo{
TempC: currentWeather.Current.TempC,
TempF: currentWeather.Current.TempF,
Status: currentWeather.Current.Condition.Text,
Country: currentWeather.Location.Country,
Region: currentWeather.Location.Region,
ImageURL: getRandomPicURL(false, currentWeather.Current.Condition.Code),
}, nil
}
func getRandomPic(directory string) string {
files, err := ioutil.ReadDir(directory)
if err != nil {
return ""
}
return files[rand.Intn(len(files))].Name()
}
func getRandomPicURL(day bool, code int) string {
var state, daytime string
if day {
daytime = "day"
} else {
daytime = "night"
}
if code == 1000 {
state = "Clear"
} else if code == 1030 || code == 1135 {
state = "Haze"
} else {
state = "Cloudy"
}
directory := fmt.Sprintf("static/pics/%s/%s", state, daytime)
return fmt.Sprintf("/%s/%s", directory, getRandomPic(directory))
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
router := gin.New()
router.Use(gin.Logger())
router.LoadHTMLGlob("templates/*.tmpl.html")
router.Static("/static", "static")
router.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "kim.tmpl.html", nil)
})
router.GET("/weather", func(c *gin.Context) {
query := c.Request.URL.Query()
lat := query.Get("lat")
long := query.Get("long")
q := fmt.Sprintf("%v,%v", lat, long)
weather, err := getWeatherInfo(q)
if err != nil {
panic(err)
}
c.JSON(http.StatusOK, weather)
})
router.Run(":" + port)
}