-
Notifications
You must be signed in to change notification settings - Fork 0
/
weatherForecast.go
200 lines (170 loc) · 4.13 KB
/
weatherForecast.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package main
import (
"encoding/json"
"io/ioutil"
"log"
"math/rand"
"net/http"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
const ()
var (
tokens []string
)
// MODELS ------------------------------------------------------------------------------------
type LoginRequest struct {
Login string
Password string
}
type LoginResponse struct {
Token string
}
type Geo struct {
Lat int
Long int
}
type Weather struct {
Weather string
Temperature int
Humidity int
}
type Request struct {
Token string
Geo Geo
Unit string
}
type Response struct {
Weather Weather
}
// FUNC --------------------------------------------------------------------------------------
func main() {
handleRequests()
}
// router
func handleRequests() {
router := mux.NewRouter()
router.HandleFunc("/api/test/{data}", test).Methods("GET") // test
router.HandleFunc("/api/weather/login", loginAttempt).Methods("POST") // login
router.HandleFunc("/api/weather", weatherForecast).Methods("POST") // weather forecast
cors := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{http.MethodGet, http.MethodPost},
AllowCredentials: true,
})
handler := cors.Handler(router)
log.Fatal(http.ListenAndServe(":10000", handler))
}
// ENDPOINTS ---------------------------------------------------------------------------------
// GET /api/test/{data}
func test(w http.ResponseWriter, r *http.Request) {
var data string
vars := mux.Vars(r)
data = vars["data"]
if len(data) < 1 {
w.WriteHeader(http.StatusBadRequest)
return
} else if len(data) > 255 {
w.WriteHeader(http.StatusRequestEntityTooLarge)
return
}
w.WriteHeader(http.StatusOK)
errEncode := json.NewEncoder(w).Encode(data)
if errEncode != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func loginAttempt(w http.ResponseWriter, r *http.Request) {
var payload LoginRequest
var token string
var response LoginResponse
request, errIO := ioutil.ReadAll(r.Body)
if errIO != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
errUnmarshal := json.Unmarshal(request, &payload)
if errUnmarshal != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if payload.Login == "user" && payload.Password == "password" {
token = uuid.New().String()
tokens = append(tokens, token)
response = LoginResponse{Token: token}
w.WriteHeader(http.StatusOK)
errEncode := json.NewEncoder(w).Encode(response)
if errEncode != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
} else {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
func weatherForecast(w http.ResponseWriter, r *http.Request) {
var payload Request
var validTokenFlag = false
var unit, weather string
var temperature int
var response Response
request, errIO := ioutil.ReadAll(r.Body)
if errIO != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
errUnmarshal := json.Unmarshal(request, &payload)
if errUnmarshal != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
// set flag if token is in token list
for _, item := range tokens {
if item == payload.Token {
validTokenFlag = true
break
}
}
// if token is valid -> check temp unit
if !validTokenFlag {
w.WriteHeader(http.StatusUnauthorized)
return
} else {
switch payload.Unit {
case "C":
unit = "C"
break
case "F":
unit = "F"
break
default:
w.WriteHeader(http.StatusBadRequest)
return
}
}
rand.Seed(time.Now().UnixNano())
// set random weather
weatherList := [7]string{"sunny", "sunny", "clear sky", "rain", "cloudy", "thunderstorm", "snow"}
weather = weatherList[rand.Intn((len(weatherList)))]
// set random temperature depending on unit
switch unit {
case "C":
temperature = rand.Intn(20 - -20) + -20
break
case "F":
temperature = rand.Intn(64 - -4) + -4
break
}
// create&send response
response = Response{Weather{Weather: weather, Temperature: temperature, Humidity: rand.Intn(80)}}
w.WriteHeader(http.StatusOK)
errEncode := json.NewEncoder(w).Encode(response)
if errEncode != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}