OpenWeather-gRPC-API/server/location.go

81 lines
1.9 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"
"os"
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...")
url := "http://api.openweathermap.org/geo/1.0/direct?q="
city := in.City
token := "&appid=" + os.Getenv("API_KEY")
url = url + city + token
2022-07-26 17:28:33 -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)
}
2022-07-26 17:28:33 -04:00
coords := []Coordinates{}
err = json.Unmarshal(body, &coords)
if err != nil {
2022-07-26 17:28:33 -04:00
log.Printf("Error decoding JSON: %v\n", err)
}
2022-07-26 17:28:33 -04:00
return &pb.SendLocation{
Latitude: coords[0].Latitude,
Longitude: coords[0].Longitude,
}, nil
}
2022-07-26 19:41:53 -04:00
// Used internally to fetch precise locations for Current and Extended
// Receives gRPC requests (interface) and the location (string)
2022-07-26 19:41:53 -04:00
// Returns the latitude (float32) and longitude (float32) for a given location
2022-07-26 23:37:38 -04:00
func getLocation(city string) (float32, float32) {
2022-07-26 19:41:53 -04:00
url := "http://api.openweathermap.org/geo/1.0/direct?q="
token := "&appid=" + os.Getenv("API_KEY")
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
}