A very specific Golang interface to the Dark Sky API for my Chrome Extension
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.5 KiB

5 years ago
  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "os"
  6. "strconv"
  7. "github.com/fvbock/endless"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func main() {
  11. apikey := os.Getenv("DARK_SKY_API_KEY")
  12. if len(apikey) == 0 {
  13. log.Fatalln("DARK_SKY_API_KEY environment variable must be set.")
  14. }
  15. router := gin.Default()
  16. router.GET("/", func(c *gin.Context) {
  17. c.Redirect(http.StatusTemporaryRedirect, "https://github.com/leothelocust/dark-sky-weather-api")
  18. })
  19. router.GET("/ping", func(c *gin.Context) {
  20. c.String(http.StatusOK, "pong")
  21. })
  22. router.GET("/current_weather/:lat/:long", func(c *gin.Context) {
  23. lat, err := strconv.ParseFloat(c.Params.ByName("lat"), 64)
  24. long, err := strconv.ParseFloat(c.Params.ByName("long"), 64)
  25. if err != nil {
  26. c.JSON(http.StatusBadRequest, gin.H{"error": "Latitude and Longitude are required"})
  27. return
  28. }
  29. response, err := currentWeather(lat, long, apikey)
  30. if err != nil {
  31. c.JSON(http.StatusExpectationFailed, gin.H{"error": err.Error()})
  32. return
  33. }
  34. c.Header("Access-Control-Allow-Origin", "*")
  35. c.JSON(http.StatusOK, gin.H{"weather": response})
  36. })
  37. err := endless.ListenAndServe("localhost:8080", router)
  38. if err != nil {
  39. log.Fatalf("Error: %s\n", err)
  40. }
  41. }
  42. func currentWeather(lat, long float64, apikey string) (ForecastResponse, error) {
  43. client := NewDarkSkyAPI(apikey)
  44. request := ForecastRequest{}
  45. request.Latitude = lat
  46. request.Longitude = long
  47. request.Options = ForecastRequestOptions{
  48. Exclude: "minutely",
  49. Lang: "en",
  50. Units: "us",
  51. }
  52. return client.Forecast(request)
  53. }