This repository was archived by the owner on Mar 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
78 lines (65 loc) · 1.67 KB
/
server.go
File metadata and controls
78 lines (65 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/addetz/go-weather-checker/apis"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
const (
TIMEOUT = 3 * time.Second
)
func main() {
// Read port if one is set
port := readPort()
// Read API key
weatherService := apis.NewWeatherService()
// Initialise echo
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Configure server
s := http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: e,
ReadTimeout: TIMEOUT,
ReadHeaderTimeout: TIMEOUT,
WriteTimeout: TIMEOUT,
IdleTimeout: TIMEOUT,
}
// Set up the root file
e.Static("/", "layout")
// Set up scripts
e.File("/scripts.js", "scripts/scripts.js")
e.File("/scripts.js.map", "scripts/scripts.js.map")
e.GET("/weather/:city", func(c echo.Context) error {
city := c.Param("city")
response, err := weatherService.GetData(city)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
return c.JSON(http.StatusOK, &apis.BackendResponse{
Message: fmt.Sprintf("Fetched data for %s", city),
FeelsLike: apis.ConvertCelsius(response.Main.FeelsLike),
Temp: apis.ConvertCelsius(response.Main.Temp),
CityName: city,
Description: response.Weather[0].Description,
})
})
log.Printf("Listening on :%s...\n", port)
if err := s.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}
// readPort reads the SERVER_PORT environment variable if one is set
// or returns a default if none is found
func readPort() string {
port, ok := os.LookupEnv("PORT")
if !ok {
return "8080"
}
return port
}