-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
54 lines (41 loc) · 1.15 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
package main
import (
"encoding/json"
"net/http"
"strings"
)
func main() {
http.HandleFunc("/hello", hello)
http.HandleFunc("/weather/", func(w http.ResponseWriter, r *http.Request) {
city := strings.SplitN(r.URL.Path, "/", 3)[2]
data, err := query(city)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(data)
})
http.ListenAndServe(":8080", nil)
}
func hello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello!"))
}
func query(city string) (weatherData, error) {
resp, err := http.Get("http://api.openweathermap.org/data/2.5/weather?q=" + city)
if err != nil {
return weatherData{}, err
}
defer resp.Body.Close()
var d weatherData
if err := json.NewDecoder(resp.Body).Decode(&d); err != nil {
return weatherData{}, err
}
return d, nil
}
type weatherData struct {
Name string `json:"name"`
Main struct {
Kelvin float64 `json:"temp"`
} `json:"main"`
}