-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.go
104 lines (94 loc) · 2.61 KB
/
server.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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"path"
)
const (
googleGeocodeURL = "http://maps.google.com/maps/api/geocode/json"
forecastURL = "https://api.forecast.io/forecast/your-api-key-here/"
rootAssetPath = "/path/to/react-weather"
)
type Location struct {
Lat float64
Lng float64
}
type GeocodeResponse struct {
Results []struct {
FormattedAddress string `json:"formatted_address"`
Geometry struct {
Location Location
}
}
}
type WeatherResponse struct {
Address string `json:"formattedAddress"`
Location Location `json:"location"`
Weather interface{} `json:"data"`
}
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/weather/", weatherHandler)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(path.Join(rootAssetPath, "www/static")))))
log.Fatal(http.ListenAndServe(":3000", nil))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, path.Join(rootAssetPath, "www/index.html"))
}
func weatherHandler(w http.ResponseWriter, r *http.Request) {
if address, ok := r.URL.Query()["address"]; ok {
address := address[0]
geo := &GeocodeResponse{}
if err := geocodeAddress(address, geo); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
location := geo.Results[0].Geometry.Location
var weather interface{}
if err := loadWeather(location, &weather); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
resp := &WeatherResponse{Address: geo.Results[0].FormattedAddress, Location: location, Weather: weather}
if err := json.NewEncoder(w).Encode(&resp); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
} else {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
}
func geocodeAddress(address string, res *GeocodeResponse) (err error) {
u, _ := url.Parse(googleGeocodeURL)
q := url.Values{}
q.Add("address", address)
u.RawQuery = q.Encode()
resp, err := http.Get(u.String())
if err != nil {
return err
}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return err
}
if len(res.Results) == 0 {
return errors.New("No Results")
}
return nil
}
func loadWeather(loc Location, res *interface{}) (err error) {
u := fmt.Sprintf("%s%f,%f", forecastURL, loc.Lat, loc.Lng)
parsed, _ := url.Parse(u)
q := url.Values{}
q.Add("exclude", "minutely,daily")
q.Add("units", "si")
parsed.RawQuery = q.Encode()
resp, err := http.Get(parsed.String())
if err != nil {
return err
}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return err
}
return nil
}