openweathermap

package module
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2022 License: Apache-2.0 Imports: 10 Imported by: 117

README

OpenWeatherMap Go API

GoDoc Build Status Coverage Status

Go (golang) package for use with openweathermap.org's API.

For more detail about the library and its features, reference your local godoc once installed.

Website!

To use the OpenweatherMap API, you need to obtain an API key. Sign up here. Once you have your key, create an environment variable called OWM_API_KEY. Start coding!

Slack Channel

Contributions welcome!

Features

Current Weather Conditions
  • By City
  • By City,St (State)
  • By City,Co (Country)
  • By City ID
  • By Zip,Co (Country)
  • By Longitude and Latitude

Forecast

Get the weather conditions for a given number of days.

  • By City
  • By City,St (State)
  • By City,Co (Country)
  • By City ID
  • By Longitude and Latitude
Access to Condition Codes and Icons

Gain access to OpenWeatherMap icons and condition codes.

  • Thunderstorms
  • Drizzle
  • Rain
  • Snow
  • Atmosphere
  • Clouds
  • Extreme
  • Additional
Data Available in Multiple Measurement Systems
  • Fahrenheit (OpenWeatherMap API - imperial)
  • Celsius (OpenWeatherMap API - metric)
  • Kelvin (OpenWeatherMap API - internal)
UV Index Data
  • Current
  • Historical
Pollution Data
  • Current

Historical Conditions

  • By Name
  • By ID
  • By Coordinates

Supported Languages

English - en, Russian - ru, Italian - it, Spanish - es (or sp), Ukrainian - uk (or ua), German - de, Portuguese - pt, Romanian - ro, Polish - pl, Finnish - fi, Dutch - nl, French - fr, Bulgarian - bg, Swedish - sv (or se), Chinese Traditional - zh_tw, Chinese Simplified - zh (or zh_cn), Turkish - tr, Croatian - hr, Catalan - ca

Installation

go get github.com/briandowns/openweathermap

Examples

There are a few full examples in the examples directory that can be referenced. 1 is a command line application and 1 is a simple web application.

package main

import (
	"log"
	"fmt"
	"os"

	// Shortening the import reference name seems to make it a bit easier
	owm "github.com/briandowns/openweathermap"
)

var apiKey = os.Getenv("OWM_API_KEY")

func main() {
	w, err := owm.NewCurrent("F", "ru", apiKey) // fahrenheit (imperial) with Russian output
	if err != nil {
		log.Fatalln(err)
	}

	w.CurrentByName("Phoenix")
	fmt.Println(w)
}

Current Conditions by location name
func main() {
    w, err := owm.NewCurrent("K", "EN", apiKey) // (internal - OpenWeatherMap reference for kelvin) with English output
    if err != nil {
        log.Fatalln(err)
    }

    w.CurrentByName("Phoenix,AZ")
    fmt.Println(w)
}
Forecast Conditions in imperial (fahrenheit) by coordinates
func main() {
    w, err := owm.NewForecast("5", "F", "FI", apiKey) // valid options for first parameter are "5" and "16"
    if err != nil {
        log.Fatalln(err)
    }

    w.DailyByCoordinates(
        &owm.Coordinates{
                Longitude: -112.07,
                Latitude: 33.45,
        },
        5 // five days forecast
    )
    fmt.Println(w)
}
Current conditions in metric (celsius) by location ID
func main() {
    w, err := owm.NewCurrent("C", "PL", apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    w.CurrentByID(2172797)
    fmt.Println(w)
}
Current conditions by zip code. 2 character country code required
func main() {
    w, err := owm.NewCurrent("F", "EN", apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    w.CurrentByZip(19125, "US")
    fmt.Println(w)
}
Configure http client
func main() {
    client := &http.Client{}
    w, err := owm.NewCurrent("F", "EN", apiKey, owm.WithHttpClient(client))
    if err != nil {
        log.Fatalln(err)
    }
}
Current UV conditions
func main() {
    uv, err := owm.NewUV(apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    coord := &owm.Coordinates{
        Longitude: 53.343497,
        Latitude:  -6.288379,
    }

    if err := uv.Current(coord); err != nil {
        log.Fatalln(err)
    }
    
    fmt.Println(coord)
}
Historical UV conditions
func main() {
    uv, err := owm.NewUV(apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    coord := &owm.Coordinates{
        Longitude: 54.995656,
        Latitude:  -7.326834,
    }

    end := time.Now().UTC()
    start := time.Now().UTC().Add(-time.Hour * time.Duration(24))

    if err := uv.Historical(coord, start, end); err != nil {
        log.Fatalln(err)
    }
}
UV Information
func main() {
    uv, err := owm.NewUV(apiKey)
    if err != nil {
        log.Fatalln(err)
    }
    
    coord := &owm.Coordinates{
    	Longitude: 53.343497,
    	Latitude:  -6.288379,
    }
    
    if err := uv.Current(coord); err != nil {
    	log.Fatalln(err)
    }

    info, err := uv.UVInformation()
    if err != nil {
        log.Fatalln(err)
    }
    
    fmt.Println(info)
}
Pollution Information
func main() {
    pollution, err := owm.NewPollution(apiKey)
    if err != nil {
        log.Fatalln(err)
    }

    params := &owm.PollutionParameters{
        Location: owm.Coordinates{
            Latitude:  0.0,
            Longitude: 10.0,
        },
        Datetime: "current",
    }

    if err := pollution.PollutionByParams(params); err != nil {
        log.Fatalln(err)
    }
}
One Call Information
func main() {
	// Possibility to exclude information. For example exclude daily information []string{ExcludeDaily}
	w, err := owm.NewOneCall("F", "EN", apiKey, []string{})
	if err != nil {
		log.Fatalln(err)
	}

	err = w.OneCallByCoordinates(
		&Coordinates{
			Longitude: -112.07,
			Latitude:  33.45,
		},
	)
	if err != nil {
		t.Error(err)
	}

	fmt.Println(w)
}

Documentation

Overview

Package openweathermap is a library for use to access the http://openweathermap.org API. JSON is the only return format supported at this time.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (
	ExcludeCurrent  = "current"
	ExcludeMinutely = "minutely"
	ExcludeHourly   = "hourly"
	ExcludeDaily    = "daily"
	ExcludeAlerts   = "alerts"
)

Exclude holds all supported excludes option to be used

Variables

View Source
var AdditionalConditions = []*ConditionData{
	{ID: 951, Meaning: "calm", Icon1: ""},
	{ID: 952, Meaning: "light breeze", Icon1: ""},
	{ID: 953, Meaning: "gentle breeze", Icon1: ""},
	{ID: 954, Meaning: "moderate breeze", Icon1: ""},
	{ID: 955, Meaning: "fresh breeze", Icon1: ""},
	{ID: 956, Meaning: "strong breeze", Icon1: ""},
	{ID: 957, Meaning: "high wind, near gale", Icon1: ""},
	{ID: 958, Meaning: "gale", Icon1: ""},
	{ID: 959, Meaning: "severe gale", Icon1: ""},
	{ID: 960, Meaning: "storm", Icon1: ""},
	{ID: 961, Meaning: "violent storm", Icon1: ""},
	{ID: 962, Meaning: "hurricane", Icon1: ""},
}

AdditionalConditions is a slive of ConditionData pointers

View Source
var AtmosphereConditions = []*ConditionData{
	{ID: 701, Meaning: "mist", Icon1: "50d.png"},
	{ID: 711, Meaning: "smoke", Icon1: "50d.png"},
	{ID: 721, Meaning: "haze", Icon1: "50d.png"},
	{ID: 731, Meaning: "sand, dust whirls", Icon1: "50d.png"},
	{ID: 741, Meaning: "fog", Icon1: "50d.png"},
	{ID: 751, Meaning: "sand", Icon1: "50d.png"},
	{ID: 761, Meaning: "dust", Icon1: "50d.png"},
	{ID: 762, Meaning: "volcanic ash", Icon1: "50d.png"},
	{ID: 771, Meaning: "squalls", Icon1: "50d.png"},
	{ID: 781, Meaning: "tornado", Icon1: "50d.png"},
}

AtmosphereConditions is a slice of ConditionData pointers

View Source
var CloudConditions = []*ConditionData{
	{ID: 800, Meaning: "clear sky", Icon1: "01d.png", Icon2: "01n.png"},
	{ID: 801, Meaning: "few clouds", Icon1: "02d.png", Icon2: " 02n.png"},
	{ID: 802, Meaning: "scattered clouds", Icon1: "03d.png", Icon2: "03d.png"},
	{ID: 803, Meaning: "broken clouds", Icon1: "04d.png", Icon2: "03d.png"},
	{ID: 804, Meaning: "overcast clouds", Icon1: "04d.png", Icon2: "04d.png"},
}

CloudConditions is a slice of ConditionData pointers

View Source
var DataUnits = map[string]string{"C": "metric", "F": "imperial", "K": "internal"}

DataUnits represents the character chosen to represent the temperature notation

View Source
var DateTimeAliases = []string{"current"}

DateTimeAliases holds the alias the pollution API supports in lieu of an ISO 8601 timestamp

View Source
var DrizzleConditions = []*ConditionData{
	{ID: 300, Meaning: "light intensity drizzle", Icon1: "09d.png"},
	{ID: 301, Meaning: "drizzle", Icon1: "09d.png"},
	{ID: 302, Meaning: "heavy intensity drizzle", Icon1: "09d.png"},
	{ID: 310, Meaning: "light intensity drizzle rain", Icon1: "09d.png"},
	{ID: 311, Meaning: "drizzle rain", Icon1: "09d.png"},
	{ID: 312, Meaning: "heavy intensity drizzle rain", Icon1: "09d.png"},
	{ID: 313, Meaning: "shower rain and drizzle", Icon1: "09d.png"},
	{ID: 314, Meaning: "heavy shower rain and drizzle", Icon1: "09d.png"},
	{ID: 321, Meaning: "shower drizzle", Icon1: "09d.png"},
}

DrizzleConditions is a slice of ConditionData pointers

View Source
var ExtremeConditions = []*ConditionData{
	{ID: 900, Meaning: "tornado", Icon1: ""},
	{ID: 901, Meaning: "tropical storm", Icon1: ""},
	{ID: 902, Meaning: "hurricane", Icon1: ""},
	{ID: 903, Meaning: "cold", Icon1: ""},
	{ID: 904, Meaning: "hot", Icon1: ""},
	{ID: 905, Meaning: "windy", Icon1: ""},
	{ID: 906, Meaning: "hail", Icon1: ""},
}

ExtremeConditions is a slice of ConditionData pointers

View Source
var IconList = []*IconData{
	{Condition: "clear sky", Day: "01d.png", Night: "01n.png"},
	{Condition: "few clouds", Day: "02d.png", Night: "02n.png"},
	{Condition: "scattered clouds", Day: "03d.png", Night: "03n.png"},
	{Condition: "broken clouds", Day: "04d.png", Night: "04n.png"},
	{Condition: "shower rain", Day: "09d.png", Night: "09n.png"},
	{Condition: "rain", Day: "10d.png", Night: "10n.png"},
	{Condition: "thunderstorm", Day: "11d.png", Night: "11n.png"},
	{Condition: "snow", Day: "13d.png", Night: "13n.png"},
	{Condition: "mist", Day: "50d.png", Night: "50n.png"},
}

IconList is a slice of IconData pointers

View Source
var LangCodes = map[string]string{
	"AF":    "Afrikaans",
	"AL":    "Albanian",
	"AR":    "Arabic",
	"AZ":    "Azerbaijani",
	"BG":    "Bulgarian",
	"CA":    "Catalan",
	"CZ":    "Czech",
	"DA":    "Danish",
	"DE":    "German",
	"EL":    "Greek",
	"EN":    "English",
	"ES":    "Spanish",
	"EU":    "Basque",
	"FA":    "Persian (Farsi)",
	"FI":    "Finnish",
	"FR":    "French",
	"GL":    "Galician",
	"HE":    "Hebrew",
	"HI":    "Hindi",
	"HR":    "Croatian",
	"HU":    "Hungarian",
	"ID":    "Indonesian",
	"IT":    "Italian",
	"JA":    "Japanese",
	"KR":    "Korean",
	"LA":    "Latvian",
	"LT":    "Lithuanian",
	"MK":    "Macedonian",
	"NL":    "Dutch",
	"NO":    "Norwegian",
	"PL":    "Polish",
	"PT":    "Portuguese",
	"PT_BR": "Português Brasil",
	"RO":    "Romanian",
	"RU":    "Russian",
	"SE":    "Swedish",
	"SK":    "Slovak",
	"SL":    "Slovenian",
	"SP":    "Spanish",
	"SR":    "Serbian",
	"SV":    "Swedish",
	"TH":    "Thai",
	"TR":    "Turkish",
	"UA":    "Ukrainian",
	"UK":    "Ukrainian",
	"VI":    "Vietnamese",
	"ZH_CN": "Chinese Simplified",
	"ZH_TW": "Chinese Traditional",
	"ZU":    "Zulu",
}

LangCodes holds all supported languages to be used inspried and sourced from @bambocher (github.com/bambocher)

View Source
var RainConditions = []*ConditionData{
	{ID: 500, Meaning: "light rain", Icon1: "09d.png"},
	{ID: 501, Meaning: "moderate rain", Icon1: "09d.png"},
	{ID: 502, Meaning: "heavy intensity rain", Icon1: "09d.png"},
	{ID: 503, Meaning: "very heavy rain", Icon1: "09d.png"},
	{ID: 504, Meaning: "extreme rain", Icon1: "09d.png"},
	{ID: 511, Meaning: "freezing rain", Icon1: "13d.png"},
	{ID: 520, Meaning: "light intensity shower rain", Icon1: "09d.png"},
	{ID: 521, Meaning: "shower rain", Icon1: "09d.png"},
	{ID: 522, Meaning: "heavy intensity shower rain", Icon1: "09d.png"},
	{ID: 531, Meaning: "ragged shower rain", Icon1: "09d.png"},
}

RainConditions is a slice of ConditionData pointers

View Source
var SnowConditions = []*ConditionData{
	{ID: 600, Meaning: "light snow", Icon1: "13d.png"},
	{ID: 601, Meaning: "snow", Icon1: "13d.png"},
	{ID: 602, Meaning: "heavy snow", Icon1: "13d.png"},
	{ID: 611, Meaning: "sleet", Icon1: "13d.png"},
	{ID: 612, Meaning: "shower sleet", Icon1: "13d.png"},
	{ID: 615, Meaning: "light rain and snow", Icon1: "13d.png"},
	{ID: 616, Meaning: "rain and snow", Icon1: "13d.png"},
	{ID: 620, Meaning: "light shower snow", Icon1: "13d.png"},
	{ID: 621, Meaning: "shower snow", Icon1: "13d.png"},
	{ID: 622, Meaning: "heavy shower snow", Icon1: "13d.png"},
}

SnowConditions is a slice of ConditionData pointers

View Source
var StationDataParameters = []string{
	"wind_dir",
	"wind_speed",
	"wind_gust",
	"temp",
	"humidity",
	"pressure",
	"rain_1h",
	"rain_24h",
	"rain_today",
	"snow",
	"lum",
	"lat",
	"long",
	"alt",
	"radiation",
	"dewpoint",
	"uv",
	"name",
}

Slice of type string of the valid parameters to be sent from a station. The API refers to this data as the "Weather station data transmission protocol"

View Source
var ThunderstormConditions = []*ConditionData{
	{ID: 200, Meaning: "thunderstorm with light rain", Icon1: "11d.png"},
	{ID: 201, Meaning: "thunderstorm with rain", Icon1: "11d.png"},
	{ID: 202, Meaning: "thunderstorm with heavy rain", Icon1: "11d.png"},
	{ID: 210, Meaning: "light thunderstorm", Icon1: "11d.png"},
	{ID: 211, Meaning: "thunderstorm", Icon1: "11d.png"},
	{ID: 212, Meaning: "heavy thunderstorm", Icon1: "11d.png"},
	{ID: 221, Meaning: "ragged thunderstorm", Icon1: "11d.png"},
	{ID: 230, Meaning: "thunderstorm with light drizzle", Icon1: "11d.png"},
	{ID: 231, Meaning: "thunderstorm with drizzle", Icon1: "11d.png"},
	{ID: 232, Meaning: "thunderstorm with heavy drizzle", Icon1: "11d.png"},
}

ThunderstormConditions is a slice of ConditionData pointers

View Source
var UVData = []UVIndexInfo{
	{
		UVIndex:               []float64{0, 2.9},
		MGC:                   "Green",
		Risk:                  "Low",
		RecommendedProtection: "Wear sunglasses on bright days; use sunscreen if there is snow on the ground, which reflects UV radiation, or if you have particularly fair skin.",
	},
	{
		UVIndex:               []float64{3, 5.9},
		MGC:                   "Yellow",
		Risk:                  "Moderate",
		RecommendedProtection: "Take precautions, such as covering up, if you will be outside. Stay in shade near midday when the sun is strongest.",
	},
	{
		UVIndex:               []float64{6, 7.9},
		MGC:                   "Orange",
		Risk:                  "High",
		RecommendedProtection: "Cover the body with sun protective clothing, use SPF 30+ sunscreen, wear a hat, reduce time in the sun within three hours of solar noon, and wear sunglasses.",
	},
	{
		UVIndex:               []float64{8, 10.9},
		MGC:                   "Red",
		Risk:                  "Very high",
		RecommendedProtection: "Wear SPF 30+ sunscreen, a shirt, sunglasses, and a wide-brimmed hat. Do not stay in the sun for too long.",
	},
	{
		UVIndex:               []float64{11},
		MGC:                   "Violet",
		Risk:                  "Extreme",
		RecommendedProtection: "Take all precautions: Wear SPF 30+ sunscreen, a long-sleeved shirt and trousers, sunglasses, and a very broad hat. Avoid the sun within three hours of solar noon.",
	},
}

UVData contains data in regards to UV index ranges, rankings, and steps for protection

Functions

func ConvertToURLValues

func ConvertToURLValues(data map[string]string) string

ConvertToURLValues will convert a map to a url.Values instance. We're taking a map[string]string instead of something more type specific since the url.Values instance only takes strings to create the URL values.

func RetrieveIcon

func RetrieveIcon(destination, iconFile string) (int64, error)

RetrieveIcon will get the specified icon from the API.

func SendStationData

func SendStationData(data url.Values)

SendStationData will send an instance the provided url.Values to the provided URL.

func ValidAPIKey

func ValidAPIKey(key string) error

ValidAPIKey makes sure that the key given is a valid one

func ValidAlias

func ValidAlias(alias string) bool

ValidAlias checks to make sure the given alias is a valid one

func ValidDataUnit

func ValidDataUnit(u string) bool

ValidDataUnit makes sure the string passed in is an accepted unit of measure to be used for the return data.

func ValidDataUnitSymbol

func ValidDataUnitSymbol(u string) bool

ValidDataUnitSymbol makes sure the string passed in is an acceptable data unit symbol.

func ValidExcludes added in v0.18.0

func ValidExcludes(e []string) (string, error)

ValidExcludes makes sure the string passed in is an acceptable excludes options.

func ValidLangCode

func ValidLangCode(c string) bool

ValidLangCode makes sure the string passed in is an acceptable lang code.

func ValidateStationDataParameter

func ValidateStationDataParameter(param string) bool

ValidateStationDataParameter will make sure that whatever parameter supplied is one that can actually be used in the POST request.

Types

type APIError

type APIError struct {
	Message string `json:"message"`
	COD     string `json:"cod"`
}

APIError returned on failed API calls.

type City

type City struct {
	ID         int         `json:"id"`
	Name       string      `json:"name"`
	Coord      Coordinates `json:"coord"`
	Country    string      `json:"country"`
	Population int         `json:"population"`
	Sys        ForecastSys `json:"sys"`
}

City data for given location

type Clouds

type Clouds struct {
	All int `json:"all"`
}

Clouds struct holds data regarding cloud cover.

type ConditionData

type ConditionData struct {
	ID      int
	Meaning string
	Icon1   string
	Icon2   string
}

ConditionData holds data structure for weather conditions information.

type Config

type Config struct {
	Mode     string // user choice of JSON or XML
	Unit     string // measurement for results to be displayed.  F, C, or K
	Lang     string // should reference a key in the LangCodes map
	APIKey   string // API Key for connecting to the OWM
	Username string // Username for posting data
	Password string // Pasword for posting data
}

Config will hold default settings to be passed into the "NewCurrent, NewForecast, etc}" functions.

func (*Config) CheckAPIKeyExists

func (c *Config) CheckAPIKeyExists() bool

CheckAPIKeyExists will see if an API key has been set.

type Coordinates

type Coordinates struct {
	Longitude float64 `json:"lon"`
	Latitude  float64 `json:"lat"`
}

Coordinates struct holds longitude and latitude data in returned JSON or as parameter data for requests using longitude and latitude.

type CurrentWeatherData

type CurrentWeatherData struct {
	GeoPos     Coordinates `json:"coord"`
	Sys        Sys         `json:"sys"`
	Base       string      `json:"base"`
	Weather    []Weather   `json:"weather"`
	Main       Main        `json:"main"`
	Visibility int         `json:"visibility"`
	Wind       Wind        `json:"wind"`
	Clouds     Clouds      `json:"clouds"`
	Rain       Rain        `json:"rain"`
	Snow       Snow        `json:"snow"`
	Dt         int         `json:"dt"`
	ID         int         `json:"id"`
	Name       string      `json:"name"`
	Cod        int         `json:"cod"`
	Timezone   int         `json:"timezone"`
	Unit       string
	Lang       string
	Key        string
	*Settings
}

CurrentWeatherData struct contains an aggregate view of the structs defined above for JSON to be unmarshaled into.

func NewCurrent

func NewCurrent(unit, lang, key string, options ...Option) (*CurrentWeatherData, error)

NewCurrent returns a new CurrentWeatherData pointer with the supplied parameters

func (*CurrentWeatherData) CurrentByArea

func (w *CurrentWeatherData) CurrentByArea()

CurrentByArea will provide the current weather for the provided area.

func (*CurrentWeatherData) CurrentByCoordinates

func (w *CurrentWeatherData) CurrentByCoordinates(location *Coordinates) error

CurrentByCoordinates will provide the current weather with the provided location coordinates.

func (*CurrentWeatherData) CurrentByID

func (w *CurrentWeatherData) CurrentByID(id int) error

CurrentByID will provide the current weather with the provided location ID.

func (*CurrentWeatherData) CurrentByName

func (w *CurrentWeatherData) CurrentByName(location string) error

CurrentByName will provide the current weather with the provided location name.

func (*CurrentWeatherData) CurrentByZip deprecated

func (w *CurrentWeatherData) CurrentByZip(zip int, countryCode string) error

CurrentByZip will provide the current weather for the provided zip code.

Deprecated: Use CurrentByZipcode instead.

func (*CurrentWeatherData) CurrentByZipcode added in v0.18.0

func (w *CurrentWeatherData) CurrentByZipcode(zip string, countryCode string) error

CurrentByZipcode will provide the current weather for the provided zip code.

type CurrentWeatherGroup added in v0.18.0

type CurrentWeatherGroup struct {
	Count int                   `json:"count"`
	List  []*CurrentWeatherData `json:"list,omitempty"`

	Unit string
	Lang string
	Key  string

	*Settings
}

CurrentWeatherGroup struct contains list of the CurrentWeatherData structs for JSON to be unmarshaled into.

func NewCurrentGroup added in v0.18.0

func NewCurrentGroup(unit, lang, key string, options ...Option) (*CurrentWeatherGroup, error)

NewCurrentGroup returns a new CurrentWeatherGroup pointer with the supplied parameters

func (*CurrentWeatherGroup) CurrentByIDs added in v0.18.0

func (g *CurrentWeatherGroup) CurrentByIDs(ids ...int) error

CurrentByIDs will provide the current weather as a list by the specified location identifiers

type DtTxt

type DtTxt struct {
	time.Time
}

func (*DtTxt) MarshalJSON

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

func (*DtTxt) UnmarshalJSON

func (dt *DtTxt) UnmarshalJSON(b []byte) error

type Forecast16WeatherData

type Forecast16WeatherData struct {
	COD     int                     `json:"cod"`
	Message string                  `json:"message"`
	City    City                    `json:"city"`
	Cnt     int                     `json:"cnt"`
	List    []Forecast16WeatherList `json:"list"`
}

Forecast16WeatherData will hold returned data from queries

func (*Forecast16WeatherData) Decode

func (f *Forecast16WeatherData) Decode(r io.Reader) error

type Forecast16WeatherList

type Forecast16WeatherList struct {
	Dt       int         `json:"dt"`
	Temp     Temperature `json:"temp"`
	Pressure float64     `json:"pressure"`
	Humidity int         `json:"humidity"`
	Weather  []Weather   `json:"weather"`
	Speed    float64     `json:"speed"`
	Deg      int         `json:"deg"`
	Clouds   int         `json:"clouds"`
	Snow     float64     `json:"snow"`
	Rain     float64     `json:"rain"`
}

Forecast16WeatherList holds specific query data

type Forecast5WeatherData

type Forecast5WeatherData struct {
	// COD     string                `json:"cod"`
	// Message float64               `json:"message"`
	City City                   `json:"city"`
	Cnt  int                    `json:"cnt"`
	List []Forecast5WeatherList `json:"list"`
}

Forecast5WeatherData will hold returned data from queries

func (*Forecast5WeatherData) Decode

func (f *Forecast5WeatherData) Decode(r io.Reader) error

type Forecast5WeatherList

type Forecast5WeatherList struct {
	Dt      int       `json:"dt"`
	Main    Main      `json:"main"`
	Weather []Weather `json:"weather"`
	Clouds  Clouds    `json:"clouds"`
	Wind    Wind      `json:"wind"`
	Rain    Rain      `json:"rain"`
	Snow    Snow      `json:"snow"`
	DtTxt   DtTxt     `json:"dt_txt"`
}

Forecast5WeatherList holds specific query data

type ForecastSys

type ForecastSys struct {
	Population int `json:"population"`
}

ForecastSys area population

type ForecastWeather

type ForecastWeather interface {
	DailyByName(location string, days int) error
	DailyByCoordinates(location *Coordinates, days int) error
	DailyByID(id, days int) error
}

type ForecastWeatherData

type ForecastWeatherData struct {
	Unit string
	Lang string
	Key  string

	*Settings
	ForecastWeatherJson
	// contains filtered or unexported fields
}

func NewForecast

func NewForecast(forecastType, unit, lang, key string, options ...Option) (*ForecastWeatherData, error)

NewForecast returns a new HistoricalWeatherData pointer with the supplied arguments.

func (*ForecastWeatherData) DailyByCoordinates

func (f *ForecastWeatherData) DailyByCoordinates(location *Coordinates, days int) error

DailyByCoordinates will provide a forecast for the coordinates ID give for the number of days given.

func (*ForecastWeatherData) DailyByID

func (f *ForecastWeatherData) DailyByID(id, days int) error

DailyByID will provide a forecast for the location ID give for the number of days given.

func (*ForecastWeatherData) DailyByName

func (f *ForecastWeatherData) DailyByName(location string, days int) error

DailyByName will provide a forecast for the location given for the number of days given.

func (*ForecastWeatherData) DailyByZip deprecated added in v0.16.0

func (f *ForecastWeatherData) DailyByZip(zip int, countryCode string, days int) error

DailyByZip will provide a forecast for the provided zip code.

Deprecated: use DailyByZipcode instead.

func (*ForecastWeatherData) DailyByZipcode added in v0.18.0

func (f *ForecastWeatherData) DailyByZipcode(zip string, countryCode string, days int) error

DailyByZipcode will provide a forecast for the provided zip code.

type ForecastWeatherJson

type ForecastWeatherJson interface {
	Decode(r io.Reader) error
}

json served by OWM API can take different forms, so all of them must be matched by corresponding data type and unmarshall method

type HistoricalParameters

type HistoricalParameters struct {
	Start int64 // Data start (unix time, UTC time zone)
	End   int64 // Data end (unix time, UTC time zone)
	Cnt   int   // Amount of returned data (one per hour, can be used instead of Data end)
}

HistoricalParameters struct holds the (optional) fields to be supplied for historical data requests.

type HistoricalWeatherData

type HistoricalWeatherData struct {
	Message  string           `json:"message"`
	Cod      int              `json:"cod"`
	CityData int              `json:"city_data"`
	CalcTime float64          `json:"calctime"`
	Cnt      int              `json:"cnt"`
	List     []WeatherHistory `json:"list"`
	Unit     string
	Key      string
	*Settings
}

HistoricalWeatherData struct is where the JSON is unmarshaled to when receiving data for a historical request.

func NewHistorical

func NewHistorical(unit, key string, options ...Option) (*HistoricalWeatherData, error)

NewHistorical returns a new HistoricalWeatherData pointer with the supplied arguments.

func (*HistoricalWeatherData) HistoryByCoord

func (h *HistoricalWeatherData) HistoryByCoord(location *Coordinates, hp *HistoricalParameters) error

HistoryByCoord will return the history for the provided coordinates

func (*HistoricalWeatherData) HistoryByID

func (h *HistoricalWeatherData) HistoryByID(id int, hp ...*HistoricalParameters) error

HistoryByID will return the history for the provided location ID

func (*HistoricalWeatherData) HistoryByName

func (h *HistoricalWeatherData) HistoryByName(location string) error

HistoryByName will return the history for the provided location

type IconData

type IconData struct {
	Condition string
	Day       string
	Night     string
}

IconData holds the relevant info for linking icons to conditions.

type Main

type Main struct {
	Temp      float64 `json:"temp"`
	TempMin   float64 `json:"temp_min"`
	TempMax   float64 `json:"temp_max"`
	FeelsLike float64 `json:"feels_like"`
	Pressure  float64 `json:"pressure"`
	SeaLevel  float64 `json:"sea_level"`
	GrndLevel float64 `json:"grnd_level"`
	Humidity  int     `json:"humidity"`
}

Main struct contains the temperates, humidity, pressure for the request.

type OneCallAlertData added in v0.18.0

type OneCallAlertData struct {
	SenderName  string   `json:"sender_name"`
	Event       string   `json:"event"`
	Start       int      `json:"start"`
	End         int      `json:"end"`
	Description string   `json:"description"`
	Tags        []string `json:"tags"`
}

type OneCallCurrentData added in v0.18.0

type OneCallCurrentData struct {
	Dt         int       `json:"dt"`
	Sunrise    int       `json:"sunrise"`
	Sunset     int       `json:"sunset"`
	Temp       float64   `json:"temp"`
	FeelsLike  float64   `json:"feels_like"`
	Pressure   int       `json:"pressure"`
	Humidity   int       `json:"humidity"`
	DewPoint   float64   `json:"dew_point"`
	Clouds     int       `json:"clouds"`
	UVI        float64   `json:"uvi"`
	Visibility int       `json:"visibility"`
	WindSpeed  float64   `json:"wind_speed"`
	WindGust   float64   `json:"wind_gust,omitempty"`
	WindDeg    float64   `json:"wind_deg"`
	Rain       Rain      `json:"rain,omitempty"`
	Snow       Snow      `json:"snow,omitempty"`
	Weather    []Weather `json:"weather"`
}

type OneCallDailyData added in v0.18.0

type OneCallDailyData struct {
	Dt        int         `json:"dt"`
	Sunrise   int         `json:"sunrise"`
	Sunset    int         `json:"sunset"`
	Moonrise  int         `json:"moonrise"`
	Moonset   int         `json:"moonset"`
	MoonPhase float64     `json:"moon_phase"`
	Temp      Temperature `json:"temp"`
	FeelsLike struct {
		Day   float64 `json:"day"`
		Night float64 `json:"night"`
		Eve   float64 `json:"eve"`
		Morn  float64 `json:"morn"`
	} `json:"feels_like"`
	Pressure  int       `json:"pressure"`
	Humidity  int       `json:"humidity"`
	DewPoint  float64   `json:"dew_point"`
	WindSpeed float64   `json:"wind_speed"`
	WindGust  float64   `json:"wind_gust,omitempty"`
	WindDeg   float64   `json:"wind_deg"`
	Clouds    int       `json:"clouds"`
	UVI       float64   `json:"uvi"`
	Pop       float64   `json:"pop"`
	Rain      float64   `json:"rain,omitempty"`
	Snow      float64   `json:"snow,omitempty"`
	Weather   []Weather `json:"weather"`
}

type OneCallData added in v0.18.0

type OneCallData struct {
	Latitude       float64               `json:"lat"`
	Longitude      float64               `json:"lon"`
	Timezone       string                `json:"timezone"`
	TimezoneOffset int                   `json:"timezone_offset"`
	Current        OneCallCurrentData    `json:"current,omitempty"`
	Minutely       []OneCallMinutelyData `json:"minutely,omitempty"`
	Hourly         []OneCallHourlyData   `json:"hourly,omitempty"`
	Daily          []OneCallDailyData    `json:"daily,omitempty"`
	Alerts         []OneCallAlertData    `json:"alerts,omitempty"`

	Unit     string
	Lang     string
	Key      string
	Excludes string
	*Settings
}

OneCallData struct contains an aggregate view of the structs defined above for JSON to be unmarshaled into.

func NewOneCall added in v0.18.0

func NewOneCall(unit, lang, key string, excludes []string, options ...Option) (*OneCallData, error)

NewCurrent returns a new OneCallData pointer with the supplied parameters

func (*OneCallData) OneCallByCoordinates added in v0.18.0

func (w *OneCallData) OneCallByCoordinates(location *Coordinates) error

OneCallByCoordinates will provide the onecall weather with the provided location coordinates.

type OneCallHourlyData added in v0.18.0

type OneCallHourlyData struct {
	Dt         int       `json:"dt"`
	Temp       float64   `json:"temp"`
	FeelsLike  float64   `json:"feels_like"`
	Pressure   int       `json:"pressure"`
	Humidity   int       `json:"humidity"`
	DewPoint   float64   `json:"dew_point"`
	UVI        float64   `json:"uvi"`
	Clouds     int       `json:"clouds"`
	Visibility int       `json:"visibility"`
	WindSpeed  float64   `json:"wind_speed"`
	WindGust   float64   `json:"wind_gust,omitempty"`
	WindDeg    float64   `json:"wind_deg"`
	Pop        float64   `json:"pop"`
	Rain       Rain      `json:"rain,omitempty"`
	Snow       Snow      `json:"snow,omitempty"`
	Weather    []Weather `json:"weather"`
}

type OneCallMinutelyData added in v0.18.0

type OneCallMinutelyData struct {
	Dt            int     `json:"dt"`
	Precipitation float64 `json:"precipitation"`
}

type Option

type Option func(s *Settings) error

Optional client settings

func WithHttpClient

func WithHttpClient(c *http.Client) Option

WithHttpClient sets custom http client when creating a new Client.

type Pollution

type Pollution struct {
	Dt       string          `json:"dt"`
	Location Coordinates     `json:"coord"`
	List     []PollutionData `json:"list"`
	Key      string
	*Settings
}

Pollution holds the data returnd from the pollution API

func NewPollution

func NewPollution(key string, options ...Option) (*Pollution, error)

NewPollution creates a new reference to Pollution

func (*Pollution) PollutionByParams

func (p *Pollution) PollutionByParams(params *PollutionParameters) error

PollutionByParams gets the pollution data based on the given parameters

type PollutionData

type PollutionData struct {
	// Coord []float64 `json:"coord"`
	// List  []struct {
	Dt   int `json:"dt"`
	Main struct {
		Aqi float64 `json:"aqi"`
	} `json:"main"`
	Components struct {
		Co   float64 `json:"co"`
		No   float64 `json:"no"`
		No2  float64 `json:"no2"`
		O3   float64 `json:"o3"`
		So2  float64 `json:"so2"`
		Pm25 float64 `json:"pm2_5"`
		Pm10 float64 `json:"pm10"`
		Nh3  float64 `json:"nh3"`
	} `json:"components"`
}

PollutionData holds the pollution specific data from the call

type PollutionParameters

type PollutionParameters struct {
	Location Coordinates
	Datetime string // this should be either ISO 8601 or an alias
}

PollutionParameters holds the parameters needed to make a call to the pollution API

type Rain

type Rain struct {
	OneH   float64 `json:"1h,omitempty"`
	ThreeH float64 `json:"3h,omitempty"`
}

Rain struct contains 3 hour data

type Settings

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

Settings holds the client settings

func NewSettings

func NewSettings() *Settings

NewSettings returns a new Setting pointer with default http client.

type Snow

type Snow struct {
	OneH   float64 `json:"1h,omitempty"`
	ThreeH float64 `json:"3h,omitempty"`
}

Snow struct contains 3 hour data

type Sys

type Sys struct {
	Type    int     `json:"type"`
	ID      int     `json:"id"`
	Message float64 `json:"message"`
	Country string  `json:"country"`
	Sunrise int     `json:"sunrise"`
	Sunset  int     `json:"sunset"`
}

Sys struct contains general information about the request and the surrounding area for where the request was made.

type Temperature

type Temperature struct {
	Day   float64 `json:"day"`
	Min   float64 `json:"min"`
	Max   float64 `json:"max"`
	Night float64 `json:"night"`
	Eve   float64 `json:"eve"`
	Morn  float64 `json:"morn"`
}

Temperature holds returned termperate sure stats

type UV

type UV struct {
	Coord []float64      `json:"coord"`
	Data  []UVDataPoints `json:"data,omitempty"`
	/*Data  []struct {
		DT    int64   `json:"dt"`
		Value float64 `json:"value"`
	} `json:"data,omitempty"`*/
	DT    int64   `json:"dt,omitempty"`
	Value float64 `json:"value,omitempty"`
	Key   string
	*Settings
}

UV contains the response from the OWM UV API

func NewUV

func NewUV(key string, options ...Option) (*UV, error)

NewUV creates a new reference to UV

func (*UV) Current

func (u *UV) Current(coord *Coordinates) error

Current gets the current UV data for the given coordinates

func (*UV) Historical

func (u *UV) Historical(coord *Coordinates, start, end time.Time) error

Historical gets the historical UV data for the coordinates and times

func (*UV) UVInformation

func (u *UV) UVInformation() ([]UVIndexInfo, error)

UVInformation provides information on the given UV data which includes the severity and "Recommended protection"

type UVDataPoints

type UVDataPoints struct {
	DT    int64   `json:"dt"`
	Value float64 `json:"value"`
}

UVDataPoints holds the UV specific data

type UVIndexInfo

type UVIndexInfo struct {
	// UVIndex holds the range of the index
	UVIndex []float64

	// MGC represents the Media graphic color
	MGC string

	// Risk of harm from unprotected sun exposure, for the average adult
	Risk string

	// RecommendedProtection contains information on what a person should
	// do when outside in the associated UVIndex
	RecommendedProtection string
}

UVIndexInfo

type Weather

type Weather struct {
	ID          int    `json:"id"`
	Main        string `json:"main"`
	Description string `json:"description"`
	Icon        string `json:"icon"`
}

Weather struct holds high-level, basic info on the returned data.

type WeatherHistory

type WeatherHistory struct {
	Main    Main      `json:"main"`
	Wind    Wind      `json:"wind"`
	Clouds  Clouds    `json:"clouds"`
	Weather []Weather `json:"weather"`
	Rain    Rain      `json:"rain"`
	Dt      int       `json:"dt"`
}

WeatherHistory struct contains aggregate fields from the above structs.

type Wind

type Wind struct {
	Speed float64 `json:"speed"`
	Deg   float64 `json:"deg"`
}

Wind struct contains the speed and degree of the wind.

Directories

Path Synopsis
_examples
cli
weather.go
weather.go
web
Example of creating a web based application purely using the net/http package to display weather information and Twitter Bootstrap so it doesn't look like it's '92.
Example of creating a web based application purely using the net/http package to display weather information and Twitter Bootstrap so it doesn't look like it's '92.

Jump to

Keyboard shortcuts

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