OpenWeather-gRPC-API/server/location.go

59 lines
1.3 KiB
Go
Raw Normal View History

package main
import (
2022-07-26 17:28:33 -04:00
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
pb "codeberg.org/andcscott/OpenWeatherMap-gRPC-API/proto"
)
2022-07-26 17:28:33 -04:00
type Coordinates struct {
Latitude float32 `json:"lat"`
Longitude float32 `json:"lon"`
}
2022-07-26 19:41:53 -04:00
// Receives a gRPC request for Location
// Returns a SendLocation message with the Latitude and Longitude
2022-07-26 17:28:33 -04:00
func (s *Server) Location(ctx context.Context, in *pb.RequestLocation) (*pb.SendLocation, error) {
log.Println("'Location' function called...")
2022-07-27 02:58:00 -04:00
lat, lon := getLocation(in.City, s.ApiKey)
2022-07-26 17:28:33 -04:00
return &pb.SendLocation{
2022-07-27 02:58:00 -04:00
Latitude: lat,
Longitude: lon,
2022-07-26 17:28:33 -04:00
}, nil
}
2022-07-26 19:41:53 -04:00
2022-07-27 02:58:00 -04:00
// Used internally to fetch precise locations
2022-07-27 03:09:11 -04:00
// Receives the city name and the server's API key
// Returns the latitude and longitude for the given location
2022-07-27 02:42:40 -04:00
func getLocation(city string, key string) (float32, float32) {
2022-07-26 19:41:53 -04:00
url := "http://api.openweathermap.org/geo/1.0/direct?q="
2022-07-27 02:42:40 -04:00
token := "&appid=" + key
2022-07-26 19:41:53 -04:00
2022-07-26 23:37:38 -04:00
url = url + city + token
2022-07-26 19:41:53 -04:00
res, err := http.Get(url)
if err != nil {
log.Printf("Error fetching location: %v\n", err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Error reading location: %v\n", err)
}
coords := []Coordinates{}
err = json.Unmarshal(body, &coords)
if err != nil {
log.Printf("Error decoding JSON: %v\n", err)
}
return coords[0].Latitude, coords[0].Longitude
}