Created
January 3, 2015 00:06
-
-
Save haldun/0b91ae8c8126fa3eab4b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"net/http" | |
"strings" | |
) | |
func main() { | |
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 query(city string) (WeatherData, error) { | |
response, err := http.Get("http://api.openweathermap.org/data/2.5/weather?q=" + city) | |
if err != nil { | |
return WeatherData{}, err | |
} | |
defer response.Body.Close() | |
var weatherData WeatherData | |
if err := json.NewDecoder(response.Body).Decode(&weatherData); err != nil { | |
return WeatherData{}, err | |
} | |
return weatherData, nil | |
} | |
type WeatherData struct { | |
Name string `json:"name"` | |
Main struct { | |
Kelvin float64 `json:"temp"` | |
} `json:"main"` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment