OpenWeather-gRPC-API/server/location.go

103 lines
2.4 KiB
Go
Raw Normal View History

package main
import (
2022-07-26 17:28:33 -04:00
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
pb "codeberg.org/andcscott/OpenWeatherMap-gRPC-API/proto"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
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...")
lat, lon, err := getLocation(in.Location.String(), s.ApiKey)
if err != nil {
return nil, fmt.Errorf("Error: %v\n", err)
}
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
func getLocation(location string, key string) (float32, float32, error) {
log.Println("'getLocation' function called...")
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
url = url + location + 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 geolocation JSON: %v\n", err)
2022-07-26 19:41:53 -04:00
}
if len(coords) < 1 {
return 0, 0, status.Error(codes.NotFound, "Location not found")
}
return coords[0].Latitude, coords[0].Longitude, nil
}
func getZipLocation(zip string, key string) (float32, float32, error) {
log.Println("'getZipLocation' function called...")
url := "https://api.openweathermap.org/geo/1.0/zip?zip="
token := "&appid=" + key
url = url + zip + token
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 geolocation JSON: %v\n", err)
}
if coords.Latitude == 0 && coords.Longitude == 0 {
return 0, 0, status.Error(codes.NotFound, "Location not found")
}
return coords.Latitude, coords.Longitude, nil
2022-07-26 19:41:53 -04:00
}