Created
September 17, 2014 21:01
-
-
Save apokalyptik/46be82fb536222a52eb6 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" | |
"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