Skip to content

Instantly share code, notes, and snippets.

@JerryNyoike
Created May 25, 2019 13:45
Show Gist options
  • Save JerryNyoike/b63a846114d613183932a4a6a01c846d to your computer and use it in GitHub Desktop.
Save JerryNyoike/b63a846114d613183932a4a6a01c846d to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"net/http"
"strings"
)
type weatherData struct {
Name string `json:"name"`
Main struct {
Kelvin float64 `json:"temp"`
} `json:"main"`
}
func main() {
http.HandleFunc("/hi", hi)
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.HandleFunc("/", hello)
http.ListenAndServe(":8080", nil)
}
func hello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello!"))
}
func hi(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello from Andela"))
}
func query(city string) (weatherData, error) {
resp, err := http.Get("http://api.openweathermap.org/data/2.5/weather?APPID=c528c674de3435a024f73a2ddcaaa9d1&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
}
func underground_weather()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment