darksky

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2020 License: MIT Imports: 11 Imported by: 0

README

go-darksky

PkgGoDev Coverage Status

Package darksky implements a client for the Dark Sky weather forecasting API.

Key features

  • Support for all Dark Sky API functionality.
  • Idomatic Go API, including support for context and Go modules.
  • Language matching.
  • Rich handling of errors, including both bad requests generic HTTP errors.
  • Fully tested, including error conditions.
  • Mock client for offline testing.
  • Monitoring hooks.

Example

func ExampleClient_Forecast() {
	c := darksky.NewClient(
		darksky.WithKey(os.Getenv("DARKSKY_KEY")),
	)

	ctx := context.Background()
	forecast, err := c.Forecast(ctx, 42.3601, -71.0589, nil, &darksky.ForecastOptions{
		Units: darksky.UnitsSI,
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(forecast)
}

License

MIT

Documentation

Overview

Package darksky implements a client for the Dark Sky weather forecasting API. See https://darksky.net/dev.

Index

Examples

Constants

View Source
const (
	// Attribution is the attribution that must be displayed.
	Attribution = "Powered by Dark Sky"

	// AttributionURL is the URL that the displayed attribution must link to.
	AttributionURL = "https://darksky.net/poweredby/"

	// DefaultBaseURL is the default base URL.
	DefaultBaseURL = "https://api.darksky.net"

	// DefaultExtend is the default extend.
	DefaultExtend = ExtendNone

	// DefaultLang is the default lang.
	DefaultLang = LangEN

	// DefaultUnits are the default units.
	DefaultUnits = UnitsUS
)

Variables

Langs is a slice of all supported languages. nolint: gochecknoglobals

Functions

This section is empty.

Types

type Alert

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

An Alert is an alert.

type Block

type Block string

A Block is a data block in a response.

const (
	BlockAlerts    Block = "alerts"
	BlockCurrently Block = "currently"
	BlockDaily     Block = "daily"
	BlockFlags     Block = "flags"
	BlockHourly    Block = "hourly"
	BlockMinutely  Block = "minutely"
)

Blocks.

type Client

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

A Client is a Dark Sky Client.

func NewClient

func NewClient(options ...ClientOption) (*Client, error)

NewClient returns a new Client.

func (*Client) Forecast

func (c *Client) Forecast(ctx context.Context, latitude, longitude float64, t *Time, options *ForecastOptions) (*Forecast, error)

Forecast returns the forecast for latitude and longitude at time t. If t is nil or zero then a forecast request is sent. If t is non-nil and non-zero then a time machine request is sent.

Example
c, err := darksky.NewClient(
	darksky.WithKey(os.Getenv("DARKSKY_KEY")),
)
if err != nil {
	fmt.Println(err)
	return
}

ctx := context.Background()
forecast, err := c.Forecast(ctx, 42.3601, -71.0589, nil, nil)
if err != nil {
	fmt.Println(err)
	return
}

// This example requests the current forecast, which varies from day to day.
// Output only that which is constant.
fmt.Println(forecast.Latitude)
fmt.Println(forecast.Longitude)
fmt.Println(forecast.Timezone)
fmt.Println(forecast.Flags.Units)
Output:

42.3601
-71.0589
America/New_York
us
Example (Minimal)
c, err := darksky.NewClient(
	darksky.WithKey(os.Getenv("DARKSKY_KEY")),
)
if err != nil {
	fmt.Println(err)
	return
}

ctx := context.Background()
forecast, err := c.Forecast(ctx, 42.3601, -71.0589, nil, &darksky.ForecastOptions{
	Units: darksky.UnitsSI,
})
if err != nil {
	fmt.Println(err)
	return
}

// The forecast varies from day to day. Print something stable.
fmt.Println(forecast.Timezone)
Output:

America/New_York
Example (TimeMachine)
c, err := darksky.NewClient(
	darksky.WithKey(os.Getenv("DARKSKY_KEY")),
)
if err != nil {
	fmt.Println(err)
	return
}

ctx := context.Background()
t := &darksky.Time{
	Time: time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC),
}
forecast, err := c.Forecast(ctx, 42.3601, -71.0589, t, nil)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(forecast.Currently.Icon)
Output:

cloudy

func (*Client) MatchLang added in v1.0.0

func (c *Client) MatchLang(strings ...string) Lang

MatchLang parses and matches the given strings until one of them matches a supported language. A string may be an Accept-Language header as handled by golang.org/x/text/language.ParseAcceptLanguage. The default language is returned if no other language matches.

type ClientOption

type ClientOption func(*Client)

A ClientOption sets an option on a Client.

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL sets the base URL.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets the HTTP Client.

func WithKey

func WithKey(key string) ClientOption

WithKey sets the key.

func WithLangs added in v1.0.0

func WithLangs(langs []Lang) ClientOption

WithLangs sets the supported languages. The first element is used as the fallback.

func WithResponseMetadataCallback

func WithResponseMetadataCallback(rmc ResponseMetadataCallback) ClientOption

WithResponseMetadataCallback sets the response metadata callback.

type Currently

type Currently struct {
	ApparentTemperature  float64 `json:"apparentTemperature"`
	CloudCover           float64 `json:"cloudCover"`
	DewPoint             float64 `json:"dewPoint"`
	Humidity             float64 `json:"humidity"`
	Icon                 Icon    `json:"icon"`
	NearestStormBearing  float64 `json:"nearestStormBearing"`
	NearestStormDistance float64 `json:"nearestStormDistance"`
	Ozone                float64 `json:"ozone"`
	PrecipIntensity      float64 `json:"precipIntensity"`
	PrecipProbability    float64 `json:"precipProbability"`
	Pressure             float64 `json:"pressure"`
	Summary              string  `json:"summary"`
	Temperature          float64 `json:"temperature"`
	Time                 *Time   `json:"time"`
	UVIndex              float64 `json:"uvIndex"`
	Visibility           float64 `json:"visibility"`
	WindBearing          float64 `json:"windBearing"`
	WindGust             float64 `json:"windGust"`
	WindSpeed            float64 `json:"windSpeed"`
}

A Currently is a current observation.

type Daily

type Daily struct {
	Data    []*DailyData `json:"data"`
	Icon    Icon         `json:"icon"`
	Summary string       `json:"summary"`
}

A Daily is a daily forecast.

type DailyData

type DailyData struct {
	ApparentTemperatureHigh     float64    `json:"apparentTemperatureHigh"`
	ApparentTemperatureHighTime *Time      `json:"apparentTemperatureHighTime"`
	ApparentTemperatureLow      float64    `json:"apparentTemperatureLow"`
	ApparentTemperatureLowTime  *Time      `json:"apparentTemperatureLowTime"`
	ApparentTemperatureMax      float64    `json:"apparentTemperatureMax"`
	ApparentTemperatureMaxTime  *Time      `json:"apparentTemperatureMaxTime"`
	ApparentTemperatureMin      float64    `json:"apparentTemperatureMin"`
	ApparentTemperatureMinTime  float64    `json:"apparentTemperatureMinTime"`
	CloudCover                  float64    `json:"cloudCover"`
	DewPoint                    float64    `json:"dewPoint"`
	Humidity                    float64    `json:"humidity"`
	Icon                        Icon       `json:"icon"`
	MoonPhase                   float64    `json:"moonPhase"`
	Ozone                       float64    `json:"ozone"`
	PrecipIntensity             float64    `json:"precipIntensity"`
	PrecipIntensityMax          float64    `json:"precipIntensityMax"`
	PrecipIntensityMaxTime      *Time      `json:"precipIntensityMaxTime"`
	PrecipProbability           float64    `json:"precipProbability"`
	PrecipType                  PrecipType `json:"precipType"`
	Pressure                    float64    `json:"pressure"`
	Summary                     string     `json:"summary"`
	SunriseTime                 *Time      `json:"sunriseTime"`
	SunsetTime                  *Time      `json:"sunsetTime"`
	TemperatureHigh             float64    `json:"temperatureHigh"`
	TemperatureHighTime         *Time      `json:"temperatureHighTime"`
	TemperatureLow              float64    `json:"temperatureLow"`
	TemperatureLowTime          *Time      `json:"temperatureLowTime"`
	TemperatureMax              float64    `json:"temperatureMax"`
	TemperatureMaxTime          *Time      `json:"temperatureMaxTime"`
	TemperatureMin              float64    `json:"temperatureMin"`
	TemperatureMinTime          *Time      `json:"temperatureMinTime"`
	Time                        *Time      `json:"time"`
	UVIndex                     float64    `json:"uvIndex"`
	UVIndexTime                 *Time      `json:"uvIndexTime"`
	Visibility                  float64    `json:"visibility"`
	WindBearing                 float64    `json:"windBearing"`
	WindGust                    float64    `json:"windGust"`
	WindGustTime                *Time      `json:"windGustTime"`
	WindSpeed                   float64    `json:"windSpeed"`
}

DailyData are daily forecast data.

type Error

type Error struct {
	Request      *http.Request
	Response     *http.Response
	ResponseBody []byte
	Details      struct {
		Code     int    `json:"code"`
		ErrorStr string `json:"error"`
	}
}

An Error is an error.

func (*Error) Error

func (e *Error) Error() string

type Extend

type Extend string

An Extend is what can be extended.

const (
	ExtendHourly Extend = "hourly"
	ExtendNone   Extend = ""
)

Extends.

type Flags

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

Flags are forecast flags.

type Forecast

type Forecast struct {
	Alerts    []*Alert   `json:"alerts"`
	Currently *Currently `json:"currently"`
	Daily     *Daily     `json:"daily"`
	Flags     *Flags     `json:"flags"`
	Hourly    *Hourly    `json:"hourly"`
	Latitude  float64    `json:"latitude"`
	Longitude float64    `json:"longitude"`
	Minutely  *Minutely  `json:"minutely"`
	Offset    float64    `json:"offset"`
	Timezone  string     `json:"timezone"`
}

A Forecast is a forecast.

type ForecastOptions

type ForecastOptions struct {
	Exclude []Block
	Extend  Extend
	Lang    Lang
	Units   Units
}

A ForecastOptions contains options for a forecast request.

type Hourly

type Hourly struct {
	Data    []*HourlyData `json:"data"`
	Icon    Icon          `json:"icon"`
	Summary string        `json:"summary"`
}

An Hourly is an hourly forecast.

type HourlyData

type HourlyData struct {
	ApparentTemperature float64    `json:"apparentTemperature"`
	CloudCover          float64    `json:"cloudCover"`
	DewPoint            float64    `json:"dewPoint"`
	Humidity            float64    `json:"humidity"`
	Icon                Icon       `json:"icon"`
	Ozone               float64    `json:"ozone"`
	PrecipIntensity     float64    `json:"precipIntensity"`
	PrecipProbability   float64    `json:"precipProbability"`
	PrecipType          PrecipType `json:"precipType"`
	Pressure            float64    `json:"pressure"`
	Summary             string     `json:"summary"`
	Temperature         float64    `json:"temperature"`
	Time                *Time      `json:"time"`
	UVIndex             float64    `json:"uvIndex"`
	Visibility          float64    `json:"visibility"`
	WindBearing         float64    `json:"windBearing"`
	WindGust            float64    `json:"windGust"`
	WindSpeed           float64    `json:"windSpeed"`
}

HourlyData are hourly forecast data.

type Icon added in v1.1.0

type Icon string

An Icon is an icon.

const (
	IconClearDay          Icon = "clear-day"
	IconClearNight        Icon = "clear-night"
	IconCloudy            Icon = "cloudy"
	IconFog               Icon = "fog"
	IconPartlyCloudyDay   Icon = "partly-cloudy-day"
	IconPartlyCloudyNight Icon = "partly-cloudy-night"
	IconRain              Icon = "rain"
	IconSleet             Icon = "sleet"
	IconSnow              Icon = "snow"
	IconWind              Icon = "wind"
)

Icons.

type Lang

type Lang string

A Lang is a language.

const (
	LangAR        Lang = "ar"          // Arabic
	LangAZ        Lang = "az"          // Azerbaijani
	LangBE        Lang = "be"          // Belarusian
	LangBG        Lang = "bg"          // Bulgarian
	LangBN        Lang = "bn"          // Bengali
	LangBS        Lang = "bs"          // Bosnian
	LangCA        Lang = "ca"          // Catalan
	LangCS        Lang = "cs"          // Czech
	LangDA        Lang = "da"          // Danish
	LangDE        Lang = "de"          // German
	LangEL        Lang = "el"          // Greek
	LangEN        Lang = "en"          // English (which is the default)
	LangEO        Lang = "eo"          // Esperanto
	LangES        Lang = "es"          // Spanish
	LangET        Lang = "et"          // Estonian
	LangFI        Lang = "fi"          // Finnish
	LangFR        Lang = "fr"          // French
	LangHE        Lang = "he"          // Hebrew
	LangHI        Lang = "hi"          // Hindi
	LangHR        Lang = "hr"          // Croatian
	LangHU        Lang = "hu"          // Hungarian
	LangID        Lang = "id"          // Indonesian
	LangIS        Lang = "is"          // Icelandic
	LangIT        Lang = "it"          // Italian
	LangJA        Lang = "ja"          // Japanese
	LangKA        Lang = "ka"          // Georgian
	LangKN        Lang = "kn"          // Kannada
	LangKO        Lang = "ko"          // Korean
	LangKW        Lang = "kw"          // Cornish
	LangLV        Lang = "lv"          // Latvian
	LangML        Lang = "ml"          // Malayam
	LangMR        Lang = "mr"          // Marathi
	LangNB        Lang = "nb"          // Norwegian Bokmål
	LangNL        Lang = "nl"          // Dutch
	LangNO        Lang = "no"          // Norwegian Bokmål (alias for nb)
	LangPA        Lang = "pa"          // Punjabi
	LangPL        Lang = "pl"          // Polish
	LangPT        Lang = "pt"          // Portuguese
	LangRO        Lang = "ro"          // Romanian
	LangRU        Lang = "ru"          // Russian
	LangSK        Lang = "sk"          // Slovak
	LangSL        Lang = "sl"          // Slovenian
	LangSR        Lang = "sr"          // Serbian
	LangSV        Lang = "sv"          // Swedish
	LangTA        Lang = "ta"          // Tamil
	LangTE        Lang = "te"          // Telugu
	LangTET       Lang = "tet"         // Tetum
	LangTR        Lang = "tr"          // Turkish
	LangUK        Lang = "uk"          // Ukrainian
	LangUR        Lang = "ur"          // Urdu
	LangXPigLatin Lang = "x-pig-latin" // Igpay Atinlay
	LangZH        Lang = "zh"          // simplified Chinese
	LangZHTW      Lang = "zh-tw"       // traditional ChineLang
)

Supported languages.

type Minutely

type Minutely struct {
	Data    []*MinutelyData `json:"data"`
	Icon    Icon            `json:"icon"`
	Summary string          `json:"summary"`
}

A Minutely is a minutely forecast.

type MinutelyData

type MinutelyData struct {
	PrecipIntensity      float64    `json:"precipIntensity"`
	PrecipIntensityError float64    `json:"precipIntensityError"`
	PrecipProbability    float64    `json:"precipProbability"`
	PrecipType           PrecipType `json:"precipType"`
	Time                 *Time      `json:"time"`
}

MinutelyData are minutely forecast data.

type PrecipType added in v1.2.0

type PrecipType string

A PrecipType is a type of precipitation.

const (
	PrecipTypeRain  PrecipType = "rain"
	PrecipTypeSleet PrecipType = "sleet"
	PrecipTypeSnow  PrecipType = "snow"
)

Precipitation types.

type ResponseMetadata

type ResponseMetadata struct {
	StatusCode       int
	ForecastAPICalls int
	ResponseTime     time.Duration
}

ResponseMetadata are extra metadata associated with a response.

type ResponseMetadataCallback

type ResponseMetadataCallback func(*ResponseMetadata)

A ResponseMetadataCallback is function that receives a ResponseMetadata.

type Severity added in v1.2.0

type Severity string

A Severity is a severity.

const (
	SeverityAdvisory Severity = "advisory"
	SeverityWatch    Severity = "watch"
	SeverityWarning  Severity = "warning"
)

Severities.

type Time

type Time struct {
	time.Time
}

A Time is a time that unmarshals from a UNIX timestamp.

func (*Time) MarshalJSON added in v1.2.1

func (t *Time) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. The time is expected to be a UNIX timestamp in seconds.

type Units

type Units string

A Units is a system of units.

const (
	UnitsAuto Units = "auto"
	UnitsCA   Units = "ca"
	UnitsSI   Units = "si"
	UnitsUK2  Units = "uk2"
	UnitsUS   Units = "us"
)

Units.

Directories

Path Synopsis
Package dstest implements a mock Dark Sky server for testing.
Package dstest implements a mock Dark Sky server for testing.
internal

Jump to

Keyboard shortcuts

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