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.

58 lines
1.1 KiB

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