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.

75 lines
1.9 KiB

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