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.

76 lines
1.9 KiB

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