Servers starts and can get data by city name

This commit is contained in:
Andrew Scott 2022-07-26 01:07:04 -04:00
parent 7e8c8ec655
commit 0b5d1b1b6b
Signed by: a
GPG key ID: 3EB62D0BBB8DB381
3 changed files with 134 additions and 0 deletions

42
server/current.go Normal file
View file

@ -0,0 +1,42 @@
package main
import (
"context"
"io/ioutil"
"log"
"net/http"
"os"
pb "codeberg.org/andcscott/OpenWeatherMap-gRPC-API/proto"
)
func getCurrent(in *pb.RequestCurrent) string {
city := in.City
url := "https://pro.openweathermap.org/data/2.5/weather?q="
token := "&appid=" + os.Getenv("API_KEY")
url = url + city + token
res, err := http.Get(url)
if err != nil {
log.Printf("Error fetching weather: %v\n", err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Error reading weather response: %v", err)
}
return string(body)
}
func (s *server) Current(ctx context.Context, in *pb.RequestCurrent) (*pb.SendCurrent, error) {
log.Println("'Current' function called...")
return &pb.SendCurrent{
Payload: getCurrent(in),
}, nil
}

52
server/location.go Normal file
View file

@ -0,0 +1,52 @@
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
pb "codeberg.org/andcscott/OpenWeatherMap-gRPC-API/proto"
)
type Index struct {
Index Coordinate `json:"0"`
}
type Coordinate struct {
Latitude string `json:"lat"`
Longitude string `json:"lon"`
}
func getLocation(in *pb.RequestCurrent) (string, string) {
log.Println("'getLocation' 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
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)
}
return "-123", "44"
}

40
server/main.go Normal file
View file

@ -0,0 +1,40 @@
package main
import (
"fmt"
"log"
"net"
"os"
"strconv"
pb "codeberg.org/andcscott/OpenWeatherMap-gRPC-API/proto"
"github.com/joho/godotenv"
"google.golang.org/grpc"
)
type server struct {
pb.WeatherServiceServer
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatalln(err)
}
port, _ := strconv.Atoi(os.Getenv("PORT"))
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatalf("Error starting server: %v\n", err)
} else {
log.Printf("Listening on port %d...\n", port)
}
s := grpc.NewServer()
pb.RegisterWeatherServiceServer(s, &server{})
if err = s.Serve(lis); err != nil {
log.Fatalf("gRPC Server error: %v\n", err)
}
}