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.

60 lines
1.4 KiB

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "os"
  6. "strconv"
  7. "github.com/fvbock/endless"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func main() {
  11. apikey := os.Getenv("DARK_SKY_API_KEY")
  12. if len(apikey) == 0 {
  13. log.Fatalln("DARK_SKY_API_KEY environment variable must be set.")
  14. }
  15. router := gin.Default()
  16. router.GET("/ping", func(c *gin.Context) {
  17. c.String(http.StatusOK, "pong")
  18. })
  19. router.GET("/current_weather/:lat/:long", func(c *gin.Context) {
  20. lat, err := strconv.ParseFloat(c.Params.ByName("lat"), 64)
  21. long, err := strconv.ParseFloat(c.Params.ByName("long"), 64)
  22. if err != nil {
  23. c.JSON(http.StatusBadRequest, gin.H{"error": "Latitude and Longitude are required"})
  24. return
  25. }
  26. response, err := currentWeather(lat, long, apikey)
  27. if err != nil {
  28. c.JSON(http.StatusExpectationFailed, gin.H{"error": err.Error()})
  29. return
  30. }
  31. c.Header("Access-Control-Allow-Origin", "*")
  32. c.JSON(http.StatusOK, gin.H{"weather": response})
  33. })
  34. err := endless.ListenAndServe("localhost:8080", router)
  35. if err != nil {
  36. log.Fatalf("Error: %s\n", err)
  37. }
  38. }
  39. func currentWeather(lat, long float64, apikey string) (ForecastResponse, error) {
  40. client := NewDarkSkyAPI(apikey)
  41. request := ForecastRequest{}
  42. request.Latitude = lat
  43. request.Longitude = long
  44. request.Options = ForecastRequestOptions{
  45. Exclude: "minutely",
  46. Lang: "en",
  47. Units: "us",
  48. }
  49. return client.Forecast(request)
  50. }