weather

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: MIT Imports: 7 Imported by: 0

README

🌦️ go-weather

Observed weather, official alerts, and geomagnetic activity for Go — one stable vocabulary over WMO codes, CAP feeds and NOAA SWPC, for any (latitude, longitude).

Go Reference Go Report Card

go-weather is the sibling of go-astronomy, and differs from it in one way worth stating first: go-astronomy computes and go-weather observes. Where the Sun is follows from a date and a coordinate, with no truth outside the arithmetic. Whether it is raining is a measurement somebody took, so it can only come from a feed.

That difference is the whole shape of the library. The core is pure — the vocabulary, and the judgement that maps a provider's values onto it — and every network call lives in an optional adapter subpackage the core does not import. A consumer that already has an observation never pulls in an HTTP client, and the core's tests run with nothing listening. There is a build gate for it: task purity fails if the core acquires net/http directly or transitively.

🚀 Quick start

go get github.com/Bugs5382/go-weather
client := openmeteo.New()
obs, err := client.Current(ctx, weather.Coordinate{Lat: 40.68, Lng: -73.94})
if err != nil {
    return err
}

fmt.Println(obs.Condition)                 // CLOUDY
fmt.Println(obs.Quantities.CloudCover)     // 0.56
fmt.Println(obs.Wind.SpeedMPH)             // 4.2
fmt.Println(obs.Stale(time.Now()))         // false, until the provider's interval passes

📦 What is in it

package what it does network
weather the vocabulary, and WMO extraction none
provider/openmeteo current conditions Open-Meteo
alert official warnings, unedited none
alert/nws United States alerts api.weather.gov
space geomagnetic activity none
space/swpc the planetary K index NOAA SWPC

Adapters are per capability, not per vendor. Open-Meteo has no alerts endpoint and NOAA SWPC does not do rain, so one provider per job is not a compromise — it is the shape the sources come in. Three feeds, three published standards, one vocabulary over the top.

🌥️ The vocabulary

Eight conditions: CLEAR, CLOUDY, FOG, RAIN, RAIN_HEAVY, SNOW, SNOW_HEAVY, THUNDERSTORM.

The grade is part of the condition because the providers grade it — WMO 61, 63 and 65 are slight, moderate and heavy rain, which is why a phone says "light rain" rather than "rain".

There is no blizzard and no whiteout, deliberately. The published definition of a blizzard requires the conditions to hold for three hours, which makes it a diagnosis applied in retrospect rather than something anybody can see happening. Heavy snow with a high wind — what a person standing outside actually sees — is already expressible as SNOW_HEAVY with a Wind beside it.

Wind sits beside the condition and never inside it: any condition can be calm or blowing hard, and a nominal speed per condition would collapse that distinction permanently.

Continuous quantities sit beside it too — cloud cover, precipitation, snowfall, visibility — because eight discrete states can only be cut between and numbers can be interpolated.

A missing reading is not a zero. Zero is a real value for every quantity: a clear sky, a dry hour, fog. When a provider gives no reading (Open-Meteo answers null where its model has no value at a place), the field stays 0 and Quantities.Missing says so. Ask with the accessors, which answer both at once:

if v, ok := obs.Quantities.VisibilityReading(); ok {
    drawHaze(v) // a measured visibility, zero included
} else {
    // no reading: draw nothing rather than fog
}

CloudCoverReading, PrecipitationReading, SnowfallReading and VisibilityReading each return (value, reported). The zero Missing means "everything reported", so a Quantities built by hand without it keeps its old meaning. A missing visibility never turns a sky into fog.

Wind works the same way. Wind.Missing flags a speed, gust or bearing the provider did not give, and SpeedReading, GustReading and DirectionReading return (value, reported), so a missing speed is never drawn as calm.

A missing condition is unknown, not clear. When Open-Meteo gives no weather_code, Observation.ConditionMissing is set and Condition is left empty (not Valid). ConditionReading returns (condition, reported). The rest of the observation still comes through.

🚨 Alerts

An alert is something a public authority has said; a condition is something the sky is doing. They are separate types so a severity can never end up driving a rendering decision, and a tornado warning under a clear sky stays a clear sky with a warning beside it.

Nothing is rephrased. The issuer's event name, headline and link travel through untouched. A paraphrase is how a warning gets softened by accident.

Absence is not safety. Report.Covered distinguishes "this place has a feed and nothing is happening" from "we have no feed here". A failed request returns the zero value, whose Covered is false — so a consumer that ignores the error still renders ignorance rather than an all-clear it was never told.

Only CAP Actual is reported. NWS publishes test messages on the live wire: of 489 alerts active nationwide when this was written, one was a Test, with the same shape as a severe thunderstorm warning. Exercise, System and Draft are filtered with it.

🚫 What it does not do

No caching, no retries, no rate limiting, no scheduling, no storage, no forecasting.

Every observation carries the provider's own expiry where the provider states one, and Observation.Stale reports against it. Where a provider states none, none is claimed and nothing is ever called stale — choosing a TTL means knowing how often you poll and how wrong you can afford to be, which is the consumer's knowledge and not the library's. A library that reaches for a cache has opinions about deployment that a library has no business having.

🧪 Tests

Every adapter is tested against recorded provider responses, which is the only way a vocabulary mapping can be checked at all: the assertion is about somebody else's field names and units, and a hand-written fixture asserts only what its author already believed.

That is not a formality. Recording real feeds is what found the live NWS test message, and what caught that the SWPC K-index product returns objects rather than the array-of-arrays with a header row that several of its sibling products use.

task test      # go test ./...
task purity    # prove the core reaches no network
task lint      # gofmt, golangci-lint, yamllint, and the above
task license   # verify the MIT header on every source file

Documentation

Overview

Package weather turns third-party weather observations into one stable vocabulary.

It is the sibling of go-astronomy and differs from it in one way worth stating first: go-astronomy computes and go-weather observes. Where the Sun is follows from a date and a coordinate, with no truth outside the arithmetic. Whether it is raining is a measurement somebody took, so it can only come from a feed.

That difference is the whole shape of the package. The core here is pure -- the vocabulary, and the judgement that maps a provider's values onto it -- and every network call lives in an optional adapter subpackage the core does not import. A consumer that already has an observation never touches the network at all, and the core's tests run with nothing listening.

The package stores nothing and schedules nothing. Every observation carries the provider's own expiry where the provider states one, and what a consumer does with that is the consumer's business: a library that reaches for a cache has opinions about deployment that a library has no business having.

It is stateless and concurrency-safe. time.Time is always a parameter and never captured at construction.

Index

Constants

View Source
const (
	// CodeInvalidCoordinate marks a latitude outside [-90, 90] or a longitude
	// outside [-180, 180].
	CodeInvalidCoordinate = 8001
	// CodeUnknownProviderCode marks a provider vocabulary value this library
	// has no mapping for. It is a real condition rather than a bug: providers
	// add codes, and answering "unknown" is honest where guessing is not.
	CodeUnknownProviderCode = 8002
	// CodeProviderUnavailable marks a provider that could not be reached or
	// that answered with a non-success status.
	CodeProviderUnavailable = 8003
	// CodeMalformedResponse marks a provider response that parsed as transport
	// but not as the shape this library expects.
	CodeMalformedResponse = 8004
)

Stable numeric error codes for the module. Each error-returning function wraps its cause with one of these via go-apperr, so a caller can recover the code with apperr.Code and branch on it without matching error strings. The values are part of the public contract: never renumber a code, only add new ones.

View Source
const ErrorServiceDigit = 8

ErrorServiceDigit is the leading digit that every go-weather error code shares, so a code is attributable to this module at a glance. It is the go-apperr service prefix for the module's code namespace. go-astronomy owns 7; this module owns 8.

Variables

View Source
var (
	// ErrInvalidCoordinate is the cause behind CodeInvalidCoordinate.
	ErrInvalidCoordinate = errors.New("weather: coordinate out of range")
	// ErrUnknownProviderCode is the cause behind CodeUnknownProviderCode.
	ErrUnknownProviderCode = errors.New("weather: unmapped provider code")
	// ErrProviderUnavailable is the cause behind CodeProviderUnavailable.
	ErrProviderUnavailable = errors.New("weather: provider unavailable")
	// ErrMalformedResponse is the cause behind CodeMalformedResponse.
	ErrMalformedResponse = errors.New("weather: malformed provider response")
)

Sentinel causes, so a caller can use errors.Is as well as read the code.

Functions

func Errors

func Errors() *apperr.Registry

Errors returns the module's go-apperr registry: the stable code table plus the presentation and logging policy around it. A consumer renders a coded error at its edge with Registry.Present (or PresentContext, which also drives the wired go-log logger) to obtain a sanitized, quotable message, looks a code up with Registry.Describe, or emits the whole table as Markdown with Registry.Markdown. The registry is built once and is safe for concurrent use.

Types

type Condition

type Condition string

Condition is what the sky is doing, as one of eight values.

The grade is part of the condition rather than a separate number, because the providers grade it: WMO codes 61, 63 and 65 are slight, moderate and heavy rain, which is why a phone says "light rain" rather than "rain". Rain and RainHeavy are different facts, not different drawings of one fact.

There is deliberately no blizzard and no whiteout. The published definition of a blizzard requires the conditions to hold for three hours, which makes it a diagnosis applied in retrospect rather than something anybody can see happening -- and heavy snow with a high wind, which is what a person standing outside actually sees, is already expressible as SnowHeavy with a Wind beside it.

const (
	Clear        Condition = "CLEAR"
	Cloudy       Condition = "CLOUDY"
	Fog          Condition = "FOG"
	Rain         Condition = "RAIN"
	RainHeavy    Condition = "RAIN_HEAVY"
	Snow         Condition = "SNOW"
	SnowHeavy    Condition = "SNOW_HEAVY"
	Thunderstorm Condition = "THUNDERSTORM"
)

The eight conditions.

func ConditionFromWMO

func ConditionFromWMO(code int, q Quantities) (Condition, error)

ConditionFromWMO maps a provider's WMO interpretation code onto the vocabulary, letting visibility overrule it where the two disagree.

Returns a CodeUnknownProviderCode error for a code with no mapping.

A visibility flagged in Missing never overrules the code. A zero VisibilityMetres is also still read as "not reported" rather than as zero visibility, because that is what it meant before Missing existed: a Quantities built by hand without the flag would otherwise fog every sky whose author left the field out, which is the more damaging reading of an absent number.

func (Condition) Valid

func (c Condition) Valid() bool

Valid reports whether c is one of the eight conditions.

type Coordinate

type Coordinate struct {
	// Lat is degrees north, in [-90, 90].
	Lat float64
	// Lng is degrees east, in [-180, 180].
	Lng float64
}

Coordinate is a place to ask about.

func (Coordinate) Validate

func (c Coordinate) Validate() error

Validate reports whether the coordinate is on the globe.

Checked before any request is made, because a bad coordinate is the caller's bug and should not cost a round trip to discover.

type Missing added in v1.0.1

type Missing struct {
	CloudCover    bool
	Precipitation bool
	Snowfall      bool
	Visibility    bool
}

Missing records, per quantity, that the provider gave no reading.

A flag for absence rather than one for presence, because only that way round is the zero value right: an adapter must say what it did not get, and a caller that builds a Quantities by hand gets reported values without having to say so.

func (Missing) Any added in v1.0.1

func (m Missing) Any() bool

Any reports whether any quantity is missing.

type Observation

type Observation struct {
	// At is the instant the observation describes.
	At time.Time
	// ExpiresAt is when the provider says its answer goes stale. Zero means
	// the provider did not say, and this library will not invent a value on
	// its behalf.
	ExpiresAt time.Time
	// Condition is the headline: one of eight, or empty where
	// ConditionMissing says the provider gave none.
	Condition Condition
	// ConditionMissing reports that the provider gave no condition, so the
	// sky is unknown. The adapter then leaves Condition empty, which is not
	// Valid, rather than letting it fall to whatever a zero code maps to: WMO
	// code 0 is a clear sky, and "no answer" is not "clear".
	//
	// Its zero value is "reported", so an Observation written without it
	// means what it meant before the flag existed.
	ConditionMissing bool
	// Quantities are what a renderer draws from.
	Quantities Quantities
	// Wind is beside the condition, never inside it.
	Wind Wind
	// ElevationMetres is the ground height the provider answered for. Carried
	// because it arrives free with the observation and because an astronomy
	// consumer wants it: the horizon dips with height, which moves sunrise by
	// minutes. This library does nothing with it.
	ElevationMetres float64
}

Observation is one answer about one place at one instant.

func (Observation) ConditionReading added in v1.1.0

func (o Observation) ConditionReading() (Condition, bool)

ConditionReading returns the condition and whether it was reported. A missing condition returns ("", false), whatever the field holds.

func (Observation) Stale

func (o Observation) Stale(now time.Time) bool

Stale reports whether the provider's own expiry has passed.

An observation whose provider stated no expiry is never stale. Answering otherwise would mean choosing a TTL, and that is the consumer's decision: it knows how often it polls and how wrong it can afford to be.

type Quantities

type Quantities struct {
	// CloudCover is 0 to 1, not a percentage.
	CloudCover float64
	// PrecipitationMMPerHour is liquid equivalent, so snow appears here too.
	PrecipitationMMPerHour float64
	// SnowfallCMPerHour is depth rather than liquid equivalent. Both are
	// carried because their ratio is how dry powder is told from wet snow,
	// and the same wind moves the two completely differently.
	SnowfallCMPerHour float64
	// VisibilityMetres is how far can be seen.
	VisibilityMetres float64

	// Missing names the quantities the provider did not report. A missing
	// quantity leaves its field at zero, and zero is a real reading for every
	// one of them: a clear sky, a dry hour, fog. Read the field only where
	// Missing says it was reported, or use the Reading accessors, which
	// answer both at once.
	//
	// Its zero value is "everything reported", so a Quantities written
	// without it means what it meant before the flag existed.
	Missing Missing
}

Quantities are the continuous values a renderer actually draws from.

Beside the condition rather than derived from it, because eight discrete states can only be cut between and numbers can be interpolated. That is the difference between weather that changes and weather that jumps, and it is what lets a consumer stay a renderer: it is handed values to draw rather than a category to interpret.

func (Quantities) CloudCoverReading added in v1.0.1

func (q Quantities) CloudCoverReading() (float64, bool)

CloudCoverReading returns the cloud cover and whether it was reported. A missing reading returns (0, false), whatever the field holds.

func (Quantities) PrecipitationReading added in v1.0.1

func (q Quantities) PrecipitationReading() (float64, bool)

PrecipitationReading returns the precipitation rate and whether it was reported. A missing reading returns (0, false), whatever the field holds.

func (Quantities) SnowfallReading added in v1.0.1

func (q Quantities) SnowfallReading() (float64, bool)

SnowfallReading returns the snowfall rate and whether it was reported. A missing reading returns (0, false), whatever the field holds.

func (Quantities) VisibilityReading added in v1.0.1

func (q Quantities) VisibilityReading() (float64, bool)

VisibilityReading returns the visibility and whether it was reported. A missing reading returns (0, false), whatever the field holds.

type Wind

type Wind struct {
	// SpeedMPH is the sustained speed. Zero is calm.
	SpeedMPH float64
	// GustMPH is the peak gust, which can far exceed the sustained speed and
	// is what actually moves a branch.
	GustMPH float64
	// FromDegrees is the bearing the wind blows *from*, the meteorological
	// convention: 270 comes out of the west and pushes towards the east, so
	// something leaning in it leans away from this bearing.
	FromDegrees float64

	// Missing names the wind readings the provider did not give. A missing
	// reading leaves its field at zero, and zero is a real reading for each:
	// a calm, a still air between gusts, a wind out of the north. Read the
	// field only where Missing says it was reported, or use the Reading
	// accessors, which answer both at once.
	//
	// Its zero value is "everything reported", so a Wind written without it
	// means what it meant before the flag existed.
	Missing WindMissing
}

Wind is how hard it is blowing and which way from.

Beside the condition and never inside it: any condition can be calm or blowing hard. Clear covers a still morning and a gale under a blue sky, and deriving a nominal speed per condition would collapse that distinction permanently -- every consumer would grow its own table and disagree with the next one.

func (Wind) DirectionReading added in v1.1.0

func (w Wind) DirectionReading() (float64, bool)

DirectionReading returns the bearing the wind blows from and whether it was reported. A missing reading returns (0, false), whatever the field holds.

func (Wind) GustReading added in v1.1.0

func (w Wind) GustReading() (float64, bool)

GustReading returns the peak gust and whether it was reported. A missing reading returns (0, false), whatever the field holds.

func (Wind) SpeedReading added in v1.1.0

func (w Wind) SpeedReading() (float64, bool)

SpeedReading returns the sustained speed and whether it was reported. A missing reading returns (0, false), whatever the field holds.

type WindMissing added in v1.1.0

type WindMissing struct {
	Speed     bool
	Gust      bool
	Direction bool
}

WindMissing records, per wind reading, that the provider gave no value.

A flag for absence rather than presence, for the reason Missing gives: only that way round is the zero value right.

func (WindMissing) Any added in v1.1.0

func (m WindMissing) Any() bool

Any reports whether any wind reading is missing.

Directories

Path Synopsis
Package alert carries official weather warnings, unedited.
Package alert carries official weather warnings, unedited.
nws
Package nws fetches official alerts from the United States National Weather Service.
Package nws fetches official alerts from the United States National Weather Service.
provider
openmeteo
Package openmeteo fetches observations from Open-Meteo.
Package openmeteo fetches observations from Open-Meteo.
Package space carries geomagnetic activity.
Package space carries geomagnetic activity.
swpc
Package swpc fetches geomagnetic activity from NOAA's Space Weather Prediction Center.
Package swpc fetches geomagnetic activity from NOAA's Space Weather Prediction Center.

Jump to

Keyboard shortcuts

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