Added location endpoint

This commit is contained in:
Andrew Scott 2022-07-26 17:28:33 -04:00
parent 971489f4ad
commit 99116a2693
Signed by: a
GPG key ID: 3EB62D0BBB8DB381
3 changed files with 34 additions and 17 deletions

View file

@ -1,6 +1,7 @@
package main
import (
"context"
"encoding/json"
"io/ioutil"
"log"
@ -10,43 +11,39 @@ import (
pb "codeberg.org/andcscott/OpenWeatherMap-gRPC-API/proto"
)
type Index struct {
Index Coordinate `json:"0"`
type Coordinates struct {
Latitude float32 `json:"lat"`
Longitude float32 `json:"lon"`
}
type Coordinate struct {
Latitude string `json:"lat"`
Longitude string `json:"lon"`
}
func getLocation(in *pb.RequestCurrent) (string, string) {
log.Println("'getLocation' function called...")
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
res, err := http.Get(url)
if err != nil {
log.Printf("Error fetching location: %v\n", err)
}
defer res.Body.Close()
log.Println(res)
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Error reading location: %v\n", err)
}
var coords []Index
coords := []Coordinates{}
err = json.Unmarshal(body, &coords)
if err != nil {
log.Println("Error reading location JSON")
log.Printf("JSON: %v\n", body)
log.Printf("Error: %v\n", err)
log.Printf("Error decoding JSON: %v\n", err)
}
return "-123", "44"
return &pb.SendLocation{
Latitude: coords[0].Latitude,
Longitude: coords[0].Longitude,
}, nil
}

19
test-client/location.go Normal file
View file

@ -0,0 +1,19 @@
package main
import (
"context"
"log"
pb "codeberg.org/andcscott/OpenWeatherMap-gRPC-API/proto"
)
func doLocation(c pb.WeatherServiceClient) {
res, err := c.Location(context.Background(), &pb.RequestLocation{
City: "Corvallis",
})
if err != nil {
log.Fatalln(err)
}
log.Printf("Latitude: %v, Longitude: %v\n", res.Latitude, res.Longitude)
}

View file

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