darksky

package module
v0.0.0-...-e4105fd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 21, 2018 License: MIT Imports: 13 Imported by: 0

README

Darksky API Client Implementation in go

GoDoc

A Simple implementation of a darksky API client.

Usage

First instantiate an api with your secret (you can sign up for free and get a secret here)

    api, err := darksky.NewAPI("my-secret")

If you need to pass a custom http client, you can use an option like this:

    api, err := darksky.NewAPI(
        "my-secret",
        darksky.HTTPClientOption(&MyCustomClient{}),
    )

It's also possible to pass a logger, for errors that are less relevant to the API user, but still relevant to report. The default logger will be logging to standard error.

    logger := log.New(os.Stderr, "Darksky API Client - ", log.LstdFlags)

    api, err := darksky.NewAPI(
        "my-secret",
        darksky.LoggerOption(logger),
    )

Then, you can query the API for forecast or time machine request like this:

    data, err := api.Forecast(42.3601, -71.0589)
    data, err := api.TimeMachine(42.3601, -71.0589, time.Now())

You can pass options to the query like this:

    data, err := api.Forecast(
        42.3601, -71.0589,
        darksky.LanguageOption(darksky.LangFR),
        ...
        )

Those options are :

  • Language through ex. LanguageOption(LangFR)
  • Extend option through ex. ExtendOption()
  • Exclude option through ex. ExcludeOption(ExMinutely, ExHourly)
  • Unit option through ex. UnitOption(UnitCA)

For more information on the API, please visit https://darksky.net/dev/docs. It is the source of most of the terminology used concerning the API parts in this project. Excerpt from the documentation has also been used as comments in the code to describe the parts that are directly in connection with the official documentation.

Documentation

Index

Examples

Constants

View Source
const (

	// ExCurrently option to exclude the Currently DataBlock from the response.
	ExCurrently = "currently"
	// ExMinutely option to exclude the Minutely DataBlock from the response.
	ExMinutely = "minutely"
	// ExHourly option to exclude the Hourly DataBlock from the response.
	ExHourly = "hourly"
	// ExDaily option to exclude the Daily DataBlock from the response.
	ExDaily = "daily"
	// ExAlerts option to exclude Alerts from the response.
	ExAlerts = "alerts"
	// ExFlags option to exclude Flags from the response.
	ExFlags = "flags"

	// LangAR => Arabic
	LangAR = "ar"
	// LangAZ => Azerbaijani
	LangAZ = "az"
	// LangBE => Belarusian
	LangBE = "be"
	// LangBG => Bulgarian
	LangBG = "bg"
	// LangBS => Bosnian
	LangBS = "bs"
	// LangCA => Catalan
	LangCA = "ca"
	// LangCS => Czech
	LangCS = "cs"
	// LangDA => Danish
	LangDA = "da"
	// LangDE => German
	LangDE = "de"
	// LangEL => Greek
	LangEL = "el"
	// LangEN => English (which is the default)
	LangEN = "en"
	// LangES : Spanish
	LangES = "es"
	// LangET => Estonian
	LangET = "et"
	// LangFI => Finnish
	LangFI = "fi"
	// LangFR => French
	LangFR = "fr"
	// LangHE => Hebrew
	LangHE = "he"
	// LangHR => Croatian
	LangHR = "hr"
	// LangHU => Hungarian
	LangHU = "hu"
	// LangID => Indonesian
	LangID = "id"
	// LangIS => Icelandic
	LangIS = "is"
	// LangIT => Italian
	LangIT = "it"
	// LangJA => Japanese
	LangJA = "ja"
	// LangKA => Georgian
	LangKA = "ka"
	// LangKO => Korean
	LangKO = "ko"
	// LangKW => Cornish
	LangKW = "kw"
	// LangLV => Latvian
	LangLV = "lv"
	// LangNB => Norwegian Bokmål
	LangNB = "nb"
	// LangNL => Dutch
	LangNL = "nl"
	// LangNO => Norwegian Bokmål (alias for nb)
	LangNO = "no"
	// LangPL => Polish
	LangPL = "pl"
	// LangPT => Portuguese
	LangPT = "pt"
	// LangRO => Romanian
	LangRO = "ro"
	// LangRU => Russian
	LangRU = "ru"
	// LangSK => Slovak
	LangSK = "sk"
	// LangSL => Slovenian
	LangSL = "sl"
	// LangSR => Serbian
	LangSR = "sr"
	// LangSV => Swedish
	LangSV = "sv"
	// LangTE =>  Tetum
	LangTE = "te"
	// LangTR => Turkish
	LangTR = "tr"
	// LangUK => Ukrainian
	LangUK = "uk"
	// LangXPIG => Igpay Atinlay
	LangXPIG = "x-pig-latin"
	// LangZH => simplified Chinese
	LangZH = "zh"
	// LangZHTW => traditional Chinese
	LangZHTW = "zh-tw"

	// UnitAuto automatically select units based on geographic location.
	UnitAuto = "auto"
	// UnitCA same as si, except that windSpeed and windGust are in kilometers per hour.
	UnitCA = "ca"
	// UnitUK2 same as si, except that nearestStormDistance and visibility are in miles, and windSpeed and windGust in miles per hour.
	UnitUK2 = "uk2"
	// UnitUS Imperial units (the default).
	UnitUS = "us"
	// UnitSI SI units.
	UnitSI = "si"
)

Variables

View Source
var (
	// ErrEmptySecret occurs when passing an empty token on api creation.
	ErrEmptySecret = errors.New("secret cannot be empty")

	// ErrNilHTTPCLient occurs when passing a nil client to the HTTPClientOption.
	ErrNilHTTPCLient = errors.New("HTTP client provided cannot be nil")

	// ErrNilLogger occurs when passing a nil logger to the LoggerOption.
	ErrNilLogger = errors.New("logger provided cannot be null")
)
View Source
var (
	// ErrLanguageNotSupported occurs when providing an option with an unsupported language.
	ErrLanguageNotSupported = errors.New("language provided is not supported")

	// ErrUnitNotSupported occurs when providing an option with an unsupported unit.
	ErrUnitNotSupported = errors.New("unit provided is not supported")

	// ErrExcludeOptionNotUnique occurs when passing non unique exclude options.
	ErrExcludeOptionNotUnique = errors.New("exclude options must be unique within the same group")
)

Functions

func HTTPError

func HTTPError(code int, txt string) error

HTTPError formats a txt error to inform it's an HTTP error and also include code.

Types

type API

type API struct {
	// contains filtered or unexported fields
}

API is used to make requests.

func NewAPI

func NewAPI(secret string, opts ...APIOption) (*API, error)

NewAPI is a helper function to create a new API.

func (API) Forecast

func (api API) Forecast(lat, lng float64, opts ...Option) (wd *APIData, err error)

Forecast query to the API.

Example
// Using a mock http client to prevent calling the real api.
api, err := NewAPI("SECRET", HTTPClientOption(ClientMock))

if err != nil {
	panic(err)
}

data, err := api.Forecast(37.8267, -122.4233,
	LanguageOption(LangEN),
	ExcludeOption(ExMinutely, ExHourly),
	UnitOption(UnitUS),
)

if err != nil {
	panic(err)
}

fmt.Printf("Current Weather: %s\n", data.Currently.Summary)
fmt.Printf("Current Temperature: %2.2f\n", data.Currently.Temperature)
Output:

Current Weather: Overcast
Current Temperature: 48.42

func (API) TimeMachine

func (api API) TimeMachine(lat, lng float64, time time.Time, opts ...Option) (*APIData, error)

TimeMachine query to the API.

Example
// Using a mock http client to prevent calling the real api.
api, err := NewAPI("SECRET", HTTPClientOption(ClientMock))

if err != nil {
	panic(err)
}

t, err := time.Parse(time.RFC822, "06 Feb 78 19:00 EST")

if err != nil {
	panic(err)
}

data, err := api.TimeMachine(37.8267, -122.4233, t,
	LanguageOption(LangEN),
	ExcludeOption(ExMinutely, ExHourly),
	UnitOption(UnitUS),
)

if err != nil {
	panic(err)
}

fmt.Printf("Current Weather: %s\n", data.Currently.Summary)
fmt.Printf("Current Temperature: %2.2f\n", data.Currently.Temperature)
fmt.Printf("Time: %s", time.Unix(data.Currently.Time, 0).Format(time.RFC822))
Output:

Current Weather: Mostly Cloudy
Current Temperature: 60.46
Time: 06 Feb 78 19:00 EST

type APIData

type APIData struct {
	Latitude  float64   `json:"latitude"`
	Longitude float64   `json:"longitude"`
	Timezone  string    `json:"timezone"`
	Currently DataPoint `json:"currently,omitempty"`
	Minutely  DataBlock `json:"minutely,omitempty"`
	Hourly    DataBlock `json:"hourly,omitempty"`
	Daily     DataBlock `json:"daily,omitempty"`
	Alerts    []Alert   `json:"alerts,omitempty"`
	Flags     Flags     `json:"flags,omitempty"`
}

APIData represents the whole payload for both request type.

type APIOption

type APIOption func(*API) error

APIOption to override defaults of the api, like the HTTP client.

func HTTPClientOption

func HTTPClientOption(c HTTPClient) APIOption

HTTPClientOption is for when you need a custom client instead of the http.DefaultCLient

func LoggerOption

func LoggerOption(l *log.Logger) APIOption

LoggerOption to add custom logging on some error less relevant for the api to return, but still want to know about.

type Alert

type Alert struct {
	Description string   `json:"description"`
	Expires     int64    `json:"expires"`
	Regions     []string `json:"regions"`
	Severity    string   `json:"severity"`
	Time        int64    `json:"time"`
	Title       string   `json:"title"`
	URI         string   `json:"uri"`
}

Alert If present, contains any severe weather alerts pertinent to the requested location.

type DataBlock

type DataBlock struct {
	Data    []DataPoint `json:"data"`
	Summary string      `json:"summary,omitempty"`
	Icon    string      `json:"icon,omitempty"`
}

DataBlock object representation from the API.

type DataPoint

type DataPoint struct {
	ApparentTemperature         float64 `json:"apparentTemperature,omitempty"`
	ApparentTemperatureHigh     float64 `json:"apparentTemperatureHigh,omitempty"`
	ApparentTemperatureHighTime int64   `json:"apparentTemperatureHighTime,omitempty"`
	ApparentTemperatureLow      float64 `json:"apparentTemperatureLow,omitempty"`
	ApparentTemperatureLowTime  int64   `json:"apparentTemperatureLowTime,omitempty"`
	CloudCover                  float64 `json:"cloudCover,omitempty"`
	DewPoint                    float64 `json:"dewPoint,omitempty"`
	Humidity                    float64 `json:"humidity,omitempty"`
	Icon                        string  `json:"icon,omitempty"`
	MoonPhase                   float64 `json:"moonPhase,omitempty"`
	NearestStormBearing         int64   `json:"nearestStormBearing,omitempty"`
	NearestStormDistance        int64   `json:"nearestStormDistance,omitempty"`
	Ozone                       float64 `json:"ozone,omitempty"`
	PrecipAccumulation          float64 `json:"precipAccumulation,omitempty"`
	PrecipIntensity             float64 `json:"precipIntensity,omitempty"`
	PrecipIntensityError        float64 `json:"precipIntensityError,omitempty"`
	PrecipIntensityMax          float64 `json:"precipIntensityMax,omitempty"`
	PrecipIntensityMaxTime      int64   `json:"precipIntensityMaxTime,omitempty"`
	PrecipProbability           float64 `json:"precipProbability,omitempty"`
	PrecipType                  string  `json:"precipType,omitempty"`
	Pressure                    float64 `json:"pressure,omitempty"`
	Summary                     string  `json:"summary,omitempty"`
	SunriseTime                 int64   `json:"sunriseTime,omitempty"`
	SunsetTime                  int64   `json:"sunsetTime,omitempty"`
	Temperature                 float64 `json:"temperature,omitempty"`
	TemperatureHigh             float64 `json:"temperatureHigh,omitempty"`
	TemperatureHighTime         int64   `json:"temperatureHighTime,omitempty"`
	TemperatureLow              float64 `json:"temperatureLow,omitempty"`
	TemperatureLowTime          int64   `json:"temperatureLowTime,omitempty"`
	Time                        int64   `json:"time"`
	UvIndex                     int64   `json:"uvIndex,omitempty"`
	UvIndexTime                 int64   `json:"uvIndexTime,omitempty"`
	Visibility                  float64 `json:"visibility,omitempty"`
	WindBearing                 float64 `json:"windBearing,omitempty"`
	WindGust                    float64 `json:"windGust,omitempty"`
	WindGustTime                int64   `json:"windGustTime,omitempty"`
	WindSpeed                   float64 `json:"windSpeed,omitempty"`
}

DataPoint object contains various properties, each representing the average (unless otherwise specified) of a particular weather phenomenon occurring during a period of time: an instant in the case of currently, a minute for minutely, an hour for hourly, and a day for daily.

type Flags

type Flags struct {
	DarkskyUnavailable string   `json:"darksky-unavailable,omitempty"`
	Sources            []string `json:"sources"`
	NearestStation     float64  `json:"nearest-station"`
	Units              string   `json:"units"`
}

Flags object contains miscellaneous metadata about the request.

type HTTPClient

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPClient let's you substitute the default http.Client for a custom one.

type Option

type Option func(*url.Values) error

Option represents options passed to the query to override default values.

func ExcludeOption

func ExcludeOption(ex ...string) Option

ExcludeOption for when you don't need all the payload, you can choose to exclude some parts.

func ExtendOption

func ExtendOption() Option

ExtendOption will gives you more data hourly.

func LanguageOption

func LanguageOption(lang string) Option

LanguageOption to have the API response in the specified language.

func UnitOption

func UnitOption(u string) Option

UnitOption to decide what unit type you want the data to be formatted to.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL