Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
type coord struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
type owmResponse struct {
Name string `json:"name"`
Coordinants coord `json:"coord"`
Main struct {
Min float64 `json:"temp_min"`
Max float64 `json:"temp_max"`
} `json:"main"`
}
var listenOn = "127.0.0.1:8888"
func init() {
flag.StringVar(&listenOn, "listen", listenOn, "The address to listen on for web requests")
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
var owmData owmResponse
vars := mux.Vars(r)
resp, _ := http.Get(fmt.Sprintf(
"http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s",
vars["lat"], vars["lon"]))
dec := json.NewDecoder(resp.Body)
dec.Decode(&owmData)
resp.Body.Close()
log.Printf("%#v", owmData)
enc, _ := json.Marshal(owmData)
w.Header().Set("Content-Type", "application/json")
w.Write(enc)
}
func main() {
flag.Parse()
r := mux.NewRouter()
r.HandleFunc("/get/{lat}/{lon}", handleRequest)
log.Fatal(http.ListenAndServe(listenOn, r))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.