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.

82 lines
2.1 KiB

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