Created
January 2, 2020 12:25
-
-
Save chew-z/7554b66b4cd5b44658c8caf23c0801d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sunset | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"reflect" | |
"time" | |
"github.com/gorilla/schema" | |
"github.com/nathan-osman/go-sunrise" | |
) | |
type request struct { | |
Lat float64 `schema:"lat"` | |
Lon float64 `schema:"lon"` | |
Date time.Time `schema:"date"` | |
} | |
type response struct { | |
Sunset string `json:"sunset"` | |
Sunrise string `json:"sunrise"` | |
} | |
/*SunTimes - All this function does is take a request | |
(which comes in as query parameters on the request URL), | |
performs a sunrise/sunset lookup, and returns a JSON-encoded response. | |
*/ | |
func SunTimes(w http.ResponseWriter, r *http.Request) { | |
var decoder = schema.NewDecoder() | |
decoder.RegisterConverter(time.Time{}, dateConverter) | |
// Parse the request from query string | |
var req request | |
if err := decoder.Decode(&req, r.URL.Query()); err != nil { | |
// Report any parsing errors | |
w.WriteHeader(http.StatusUnprocessableEntity) | |
fmt.Fprintf(w, "Error: %s", err) | |
return | |
} | |
log.Printf("Date %v, Lat %v, Lon %v", req.Date, req.Lat, req.Lon) | |
if req.Date.IsZero() { | |
req.Date = time.Now() | |
} | |
if req.Lat == 0 && req.Lon == 0 { | |
req.Lat = 52.237 | |
req.Lon = 21.017 | |
} | |
// Perform sunrise/sunset calculation | |
sunrise, sunset := sunrise.SunriseSunset( | |
req.Lat, req.Lon, | |
req.Date.Year(), req.Date.Month(), req.Date.Day(), | |
) | |
location, _ := time.LoadLocation("Europe/Warsaw") | |
set := sunset.In(location).Format("15:04:05") | |
rise := sunrise.In(location).Format("15:04:05") | |
// Send response back to client as JSON | |
w.WriteHeader(http.StatusOK) | |
response := response{set, rise} | |
if err := json.NewEncoder(w).Encode(&response); err != nil { | |
panic(err) | |
} | |
} | |
func dateConverter(value string) reflect.Value { | |
s, _ := time.Parse("2006-01-_2", value) | |
return reflect.ValueOf(s) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment