-
Notifications
You must be signed in to change notification settings - Fork 30
/
main.go
110 lines (91 loc) · 2.44 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
108
109
110
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/go-chi/chi"
)
func main() {
var err error
time.Local, err = time.LoadLocation("America/New_York")
if err != nil {
panic("timezone not loaded!")
}
mux := chi.NewRouter()
mux.Get("/health", health)
mux.Get("/", handler)
log.Println("listening on :3000")
http.ListenAndServe(":3000", mux)
}
func health(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok " + time.Now().Format(time.RFC3339)))
}
func handler(w http.ResponseWriter, r *http.Request) {
lat := r.URL.Query().Get("lat")
if lat == "" {
lat = "41.495833"
}
lng := r.URL.Query().Get("lng")
if lng == "" {
lng = "-81.685278"
}
date, _ := time.Parse(time.RFC3339, r.URL.Query().Get("date"))
if date.IsZero() {
date = time.Now()
}
u := fmt.Sprintf(
"https://api.sunrise-sunset.org/json?lat=%s&lng=%s&date=%s&formatted=0",
lat,
lng,
date.Format("2006-01-02"),
)
log.Println("sending request to", u)
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("couldn't make http request"))
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Errorf("http: do: %w", err).Error()))
return
}
var target struct {
Status string `json:"status"`
Results struct {
Sunrise time.Time `json:"sunrise"`
Sunset time.Time `json:"sunset"`
SolarNoon time.Time `json:"solar_noon"`
} `json:"results"`
}
if err := json.NewDecoder(resp.Body).Decode(&target); err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("couldn't decode json"))
return
}
resp.Body.Close()
out := struct {
OK bool `json:"ok"`
Date string `json:"date"`
Sunrise string `json:"sunrise"`
Sunset string `json:"sunset"`
SolarNoon string `json:"solar_noon"`
}{
OK: true,
Date: date.Format("2006-01-02"),
Sunrise: target.Results.Sunrise.In(time.Local).Format("3:04 PM"),
Sunset: target.Results.Sunset.In(time.Local).Format("3:04 PM"),
SolarNoon: target.Results.SolarNoon.In(time.Local).Format("3:04 PM"),
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(out)
}