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.

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