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.

56 lines
1.1 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/google/go-querystring/query"
  6. )
  7. // DarkSky API endpoint
  8. var (
  9. BaseURL = "https://api.darksky.net/forecast"
  10. )
  11. // DarkSky Api client
  12. type DarkSky interface {
  13. Forecast(request ForecastRequest) (ForecastResponse, error)
  14. }
  15. type darkSky struct {
  16. APIKey string
  17. Client *http.Client
  18. }
  19. // NewDarkSkyAPI creates a new DarkSky client
  20. func NewDarkSkyAPI(apiKey string) DarkSky {
  21. return &darkSky{apiKey, &http.Client{}}
  22. }
  23. // Forecast request a forecast
  24. func (d *darkSky) Forecast(request ForecastRequest) (ForecastResponse, error) {
  25. response := ForecastResponse{}
  26. url := d.buildRequestURL(request)
  27. err := get(d.Client, url, &response)
  28. return response, err
  29. }
  30. func (d *darkSky) buildRequestURL(request ForecastRequest) string {
  31. url := fmt.Sprintf("%s/%s/%f,%f", BaseURL, d.APIKey, request.Latitude, request.Longitude)
  32. if request.Time > 0 {
  33. url = url + fmt.Sprintf(",%d", request.Time)
  34. }
  35. values, _ := query.Values(request.Options)
  36. queryString := values.Encode()
  37. if len(queryString) > 0 {
  38. url = url + "?" + queryString
  39. }
  40. return url
  41. }