/
main.go
74 lines (66 loc) · 2.01 KB
/
main.go
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
package main
import (
"encoding/json"
"net/http"
"os"
"strconv"
"github.com/EntilZha/chapelco-weather-goajs/weather"
"github.com/gorilla/mux"
)
func currentWeatherHandler(w http.ResponseWriter, r *http.Request) {
response, err := json.Marshal(weather.ReadCurrentWeatherRecord())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
func pastWeatherRecordsHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
n, err := strconv.Atoi(params["n"])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response, err := json.Marshal(weather.ReadLastNWeatherRecords(n))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
func pastWeatherListsHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
n, err := strconv.Atoi(params["n"])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response, err := json.Marshal(weather.ReadLastNWeatherRecordsToMap(n))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
func getPort() string {
var port = os.Getenv("PORT")
// Set a default port if there is nothing in the environment
if port == "" {
port = "8080"
}
return ":" + port
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/api/weather/current", currentWeatherHandler)
router.HandleFunc("/api/weather/past-record-list/{n}", pastWeatherRecordsHandler)
router.HandleFunc("/api/weather/past-field-lists/{n}", pastWeatherListsHandler)
router.PathPrefix("/").Handler(http.FileServer(http.Dir("angular/app")))
router.PathPrefix("/bower_components").Handler(http.FileServer(http.Dir("angular/app/bower_components")))
http.Handle("/", router)
http.ListenAndServe(getPort(), nil)
}