Units, City, and Zip lookups ok, need to handle unspecified location

This commit is contained in:
Andrew Scott 2022-09-01 20:16:07 -04:00
parent b924b8486f
commit 2ea7920ca2
Signed by: a
GPG key ID: 3EB62D0BBB8DB381
3 changed files with 31 additions and 14 deletions

View file

@ -8,48 +8,65 @@ import (
"net/http"
pb "codeberg.org/andcscott/OpenWeatherMap-gRPC-API/proto"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func (s *Server) createFiveDayUrl(in *pb.RequestFiveDay) (string, error) {
var lat, lon float32
var units string
var err error
url := "https://api.openweathermap.org/data/2.5/forecast?"
units := "&units="
switch in.Units {
case pb.Units_UNITS_IMPERIAL:
units = "imperial"
units += "imperial"
case pb.Units_UNITS_METRIC:
units = "metric"
units += "metric"
default:
units = "standard"
units += "standard"
}
if in.LocationType == pb.LocationType_LOCATION_TYPE_COORDS {
switch in.LocationType {
case pb.LocationType_LOCATION_TYPE_CITY:
lat, lon, err = getLocation(in.Location.GetCity(), s.ApiKey)
if err != nil {
return "", err
}
case pb.LocationType_LOCATION_TYPE_ZIP_CODE:
lat, lon, err = getZipLocation(in.Location.GetZipCode(), s.ApiKey)
if err != nil {
return "", err
}
case pb.LocationType_LOCATION_TYPE_COORDS:
lat = in.Location.GetCoords().Latitude
lon = in.Location.GetCoords().Longitude
} else {
default:
lat, lon, err = getLocation(in.Location.String(), s.ApiKey)
if err != nil {
return "", fmt.Errorf("Error: %v\n", err)
return "", err
}
}
url = url + fmt.Sprintf("lat=%f", lat) + fmt.Sprintf("&lon=%f", lon) + units
return url, err
return url, nil
}
// Receives a gRPC request for an extended forecast
// Returns a SendExtended message with the forecast in JSON
func (s *Server) FiveDay(ctx context.Context, in *pb.RequestFiveDay) (*pb.SendFiveDay, error) {
log.Println("'Extended' function called...")
log.Println("'FiveDay' function called...")
url, err := s.createFiveDayUrl(in)
if err != nil {
return nil, err
return nil, status.Errorf(
codes.InvalidArgument,
fmt.Sprintf("Invalid location: %s", in.Location.String()),
)
}
token := "&appid=" + s.ApiKey
res, err := http.Get(url + token)

View file

@ -11,10 +11,10 @@ func doFiveDay(c pb.WeatherServiceClient) {
res, err := c.FiveDay(context.Background(), &pb.RequestFiveDay{
LocationType: pb.LocationType_LOCATION_TYPE_CITY,
Units: pb.Units_UNITS_IMPERIAL,
Units: pb.Units_UNITS_METRIC,
Location: &pb.OneOfLocation{
LocationId: &pb.OneOfLocation_City{
City: "Corvalls",
City: "",
},
},
})

View file

@ -19,6 +19,6 @@ func main() {
c := pb.NewWeatherServiceClient(conn)
//doCurrent(c)
//doExtended(c)
doLocation(c)
doFiveDay(c)
//doLocation(c)
}