Skip to content
Snippets Groups Projects
Commit 92c46882 authored by Johannes Borgen's avatar Johannes Borgen
Browse files

parameterized the weather handler with input validation

parent 0e830aa5
Branches
No related tags found
1 merge request!4Finished app
...@@ -51,10 +51,21 @@ func WeatherHandler(w http.ResponseWriter, r *http.Request) { ...@@ -51,10 +51,21 @@ func WeatherHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method { switch r.Method {
case http.MethodGet: case http.MethodGet:
var result = FinalReport{} var result = FinalReport{}
lat := r.FormValue("lat")
long := r.FormValue("long")
result, err := GetSingleForecast(58.8569687273594, 5.85660630854479) latitude, err := GetFloat(lat)
longitude, err2 := GetFloat(long)
// If input is not valid throw error
if err != nil || err2 != nil || longitude == 0 || latitude == 0 {
http.Error(w, "Latitude/Longitude must be valid floats", http.StatusBadRequest)
return
}
result, err = GetSingleForecast(latitude, longitude)
if err != nil { if err != nil {
fmt.Println("Handler request err: ", err) http.Error(w, "Could not get forecast", http.StatusInternalServerError)
} }
w.Header().Set("content-type", "application/json") w.Header().Set("content-type", "application/json")
...@@ -69,6 +80,15 @@ func WeatherHandler(w http.ResponseWriter, r *http.Request) { ...@@ -69,6 +80,15 @@ func WeatherHandler(w http.ResponseWriter, r *http.Request) {
} }
} }
// Checks and returns valid float64
func GetFloat(query string) (float64, error) {
result, err := strconv.ParseFloat(query, 64)
if err == nil {
return result, nil
}
return 0, err
}
// Parses the response from Metrologisk institutt, // Parses the response from Metrologisk institutt,
func ParseWeatherData(data []ForecastData) (FinalReport, error) { func ParseWeatherData(data []ForecastData) (FinalReport, error) {
var result = FinalReport{} var result = FinalReport{}
...@@ -79,7 +99,7 @@ func ParseWeatherData(data []ForecastData) (FinalReport, error) { ...@@ -79,7 +99,7 @@ func ParseWeatherData(data []ForecastData) (FinalReport, error) {
// Sort thorugh the response // Sort thorugh the response
for i := 0; i < len(data); i++ { for i := 0; i < len(data); i++ {
// Format time.Time values for easier to read output // Format time.Time values for easier to read output
date := data[i].From.Format("02/01/06") date := data[i].From.Format("01/02/06")
hour := data[i].From.Format("15:04") hour := data[i].From.Format("15:04")
// Condition for an object containing temperature data, other field not populated // Condition for an object containing temperature data, other field not populated
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment