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.

77 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.Static("/public", "./public")
  26. router.GET("/ping", func(c *gin.Context) {
  27. c.String(http.StatusOK, "pong")
  28. })
  29. cacheDuration := time.Minute * 15
  30. cacheStore := persistence.NewInMemoryStore(cacheDuration)
  31. router.GET("/current_weather/:lat/:long", cache.CachePage(cacheStore, cacheDuration, func(c *gin.Context) {
  32. lat, err := strconv.ParseFloat(c.Params.ByName("lat"), 64)
  33. long, err := strconv.ParseFloat(c.Params.ByName("long"), 64)
  34. if err != nil {
  35. c.JSON(http.StatusBadRequest, gin.H{"error": "Latitude and Longitude are required"})
  36. return
  37. }
  38. response, err := currentWeather(lat, long, apikey)
  39. if err != nil {
  40. c.JSON(http.StatusExpectationFailed, gin.H{"error": err.Error()})
  41. log.Printf("Error: %s\n", err)
  42. return
  43. }
  44. c.Header("Access-Control-Allow-Origin", "*")
  45. c.JSON(http.StatusOK, gin.H{"weather": response})
  46. }))
  47. if os.Getenv("GIN_MODE") == "release" {
  48. log.Fatal(autotls.Run(router, "weather.l3vi.co"))
  49. } else {
  50. log.Fatal(router.Run(":3010"))
  51. }
  52. }
  53. func currentWeather(lat, long float64, apikey string) (ForecastResponse, error) {
  54. client := NewDarkSkyAPI(apikey)
  55. request := ForecastRequest{}
  56. request.Latitude = lat
  57. request.Longitude = long
  58. request.Options = ForecastRequestOptions{
  59. Exclude: "minutely",
  60. Lang: "en",
  61. Units: "us",
  62. }
  63. return client.Forecast(request)
  64. }