Initial checkin

This commit is contained in:
Winni Neessen 2023-05-12 12:44:27 +02:00
parent ad65aa77dd
commit 2ed373adf0
Signed by: wneessen
GPG key ID: 385AC9889632126E
10 changed files with 489 additions and 2 deletions

14
.gitignore vendored
View file

@ -1,6 +1,7 @@
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
# SPDX-FileCopyrightText: 2023 Winni Neessen <winni@neessen.dev>
#
# SPDX-License-Identifier: CC0-1.0
# Binaries for programs and plugins
*.exe
*.exe~
@ -19,3 +20,12 @@
# Go workspace file
go.work
# IdeaJ
.idea
# Example code
examples
# Environment files
.env

15
.golangci.toml Normal file
View file

@ -0,0 +1,15 @@
## SPDX-FileCopyrightText: 2022 Winni Neessen <winni@neessen.dev>
##
## SPDX-License-Identifier: MIT
[run]
go = "1.20"
tests = true
[linters]
enable = ["stylecheck", "whitespace", "containedctx", "contextcheck", "decorder",
"errname", "errorlint", "gofmt", "gofumpt", "goimports"]
[linters-settings.goimports]
local-prefixes = "github.com/wneessen/go-meteologix"

121
LICENSES/CC0-1.0.txt Normal file
View file

@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

9
LICENSES/MIT.txt Normal file
View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,2 +1,8 @@
<!--
SPDX-FileCopyrightText: 2023 Winni Neessen <winni@neessen.dev>
SPDX-License-Identifier: CC0-1.0
-->
# go-meteologix
Go bindings to the Meteologix/Kachelmann weather API

9
doc.go Normal file
View file

@ -0,0 +1,9 @@
// SPDX-FileCopyrightText: 2023 Winni Neessen <winni@neessen.dev>
//
// SPDX-License-Identifier: MIT
// Package meteologix provides bindings to the Meteologix/Kachelmann weather API
package meteologix
// VERSION represents the current version of the package
const VERSION = "0.0.1"

7
go.mod Normal file
View file

@ -0,0 +1,7 @@
// SPDX-FileCopyrightText: 2023 Winni Neessen <winni@neessen.dev>
//
// SPDX-License-Identifier: MIT
module github.com/wneessen/go-meteologix
go 1.20

106
httpclient.go Normal file
View file

@ -0,0 +1,106 @@
// SPDX-FileCopyrightText: 2023 Winni Neessen <winni@neessen.dev>
//
// SPDX-License-Identifier: MIT
package meteologix
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
const (
// HTTPClientTimeout is the default timeout value for the HTTPClient
HTTPClientTimeout = time.Second * 10
// MIMETypeJSON is a string constant for application/json MIME type
MIMETypeJSON = "application/json"
)
// ErrNonJSONResponse is returned when a HTTPClient request did not return the
// expected application/json content type
var ErrNonJSONResponse = errors.New("HTTP response is of non-JSON content type")
// HTTPClient is a type wrapper for the Go stdlib http.Client and the Config
type HTTPClient struct {
*Config
*http.Client
}
// NewHTTPClient returns a new HTTP client
func NewHTTPClient(c *Config) *HTTPClient {
tc := &tls.Config{
MaxVersion: tls.VersionTLS12,
MinVersion: tls.VersionTLS12,
}
ht := http.Transport{TLSClientConfig: tc}
hc := &http.Client{Transport: &ht}
return &HTTPClient{c, hc}
}
// Get performs a HTTP GET request for the given URL with the default HTTP timeout
func (hc *HTTPClient) Get(u string) ([]byte, error) {
return hc.GetWithTimeout(u, HTTPClientTimeout)
}
// GetWithTimeout performs a HTTP GET request for the given URL and sets a timeout
// context with the given timeout duration
func (hc *HTTPClient) GetWithTimeout(u string, t time.Duration) ([]byte, error) {
ctx, cfn := context.WithTimeout(context.Background(), t)
defer cfn()
hr, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, err
}
hr.Header.Set("User-Agent", hc.ua)
hr.Header.Set("Content-Type", MIMETypeJSON)
hr.Header.Set("Accept", MIMETypeJSON)
hr.Header.Set("Accept-Language", hc.al)
// User authentication (only required for Meteologix API calls)
if strings.HasPrefix(u, APIBaseURL) {
hc.setAuthHeader(hr)
}
sr, err := hc.Do(hr)
if err != nil {
return nil, err
}
defer func() {
if err := sr.Body.Close(); err != nil {
_, _ = fmt.Fprintln(os.Stderr, "failed to close HTTP request body", err)
}
}()
if !strings.HasPrefix(sr.Header.Get("Content-Type"), MIMETypeJSON) {
return nil, ErrNonJSONResponse
}
buf := &bytes.Buffer{}
bw := bufio.NewWriter(buf)
_, err = io.Copy(bw, sr.Body)
if err != nil {
return nil, fmt.Errorf("failed to copy HTTP response body to buffer: %w", err)
}
return buf.Bytes(), nil
}
// setAuthHeader sets the corresponding user authentication header. If an API Key is set, this
// will be preferred, alternatively a username/password combination for HTTP Basic auth can
// be used
func (hc *HTTPClient) setAuthHeader(hr *http.Request) {
if hc.ak != "" {
hr.Header.Set("X-API-Key", hc.Config.ak)
return
}
if hc.un != "" && hc.pw != "" {
hr.SetBasicAuth(hc.un, hc.pw)
}
}

90
location.go Normal file
View file

@ -0,0 +1,90 @@
package meteologix
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"sort"
"strconv"
)
// OSMNominatimURL is the API endpoint URL for the OpenStreetMaps Nominatim API
const OSMNominatimURL = "https://nominatim.openstreetmap.org/search"
// ErrCityNotFound is returned if a requested city was not found in the OSM API
var ErrCityNotFound = errors.New("requested city not found in OSM Nominatim API")
// GeoLocation represent the GPS GeoLocation coordinates of a City
type GeoLocation struct {
// Importance is the OSM computed importance rank
Importance float64 `json:"importance"`
// Latitude represents the GPS Latitude coordinates of the requested City as Float
Latitude float64
// LatitudeString represents the GPS Latitude coordinates of the requested City as string
LatitudeString string `json:"lat"`
// Longitude represents the GPS Longitude coordinates of the requested City as Float
Longitude float64
// LongitudeString represents the GPS Longitude coordinates of the requested City as String
LongitudeString string `json:"lon"`
// Name represents the requested City
Name string `json:"display_name"`
// PlaceID is the OSM Nominatim internal database ID
PlaceID int64 `json:"place_id"`
}
// GetGeoLocationByCity returns the GeoLocation with the highest importance based on
// the given City name
//
// This method makes use of the OSM Nominatim API
func (c *Client) GetGeoLocationByCity(ci string) (GeoLocation, error) {
ga, err := c.GetGeoLocationsByCity(ci)
return ga[0], err
}
// GetGeoLocationsByCity returns a slice of GeoLocation based on the requested City name
// The returned slice will be sorted by Importance of the results with the highest
// importance as first entry
//
// This method makes use of the OSM Nominatim API
func (c *Client) GetGeoLocationsByCity(ci string) ([]GeoLocation, error) {
ga := make([]GeoLocation, 0)
u, err := url.Parse(OSMNominatimURL)
if err != nil {
return ga, fmt.Errorf("failed to parse OSM Nominatim URL: %w", err)
}
uq := u.Query()
uq.Add("format", "json")
uq.Add("q", ci)
u.RawQuery = uq.Encode()
r, err := c.hc.Get(u.String())
if err != nil {
return ga, fmt.Errorf("OSM Nominatim API request failed: %w", err)
}
var la []GeoLocation
if err := json.Unmarshal(r, &la); err != nil {
return ga, fmt.Errorf("failed to unmarshal API response JSON: %w", err)
}
if len(la) < 1 {
return ga, ErrCityNotFound
}
for _, l := range la {
lat, err := strconv.ParseFloat(l.LatitudeString, 64)
if err != nil {
return ga, fmt.Errorf("failed to convert latitude string to float value: %w", err)
}
lon, err := strconv.ParseFloat(l.LongitudeString, 64)
if err != nil {
return ga, fmt.Errorf("failed to convert longitude string to float value: %w", err)
}
l.Latitude = lat
l.Longitude = lon
ga = append(ga, l)
}
sort.SliceStable(ga, func(i, j int) bool { return ga[i].Importance > ga[j].Importance })
return ga, nil
}

114
meteologix.go Normal file
View file

@ -0,0 +1,114 @@
// SPDX-FileCopyrightText: 2023 Winni Neessen <winni@neessen.dev>
//
// SPDX-License-Identifier: MIT
package meteologix
// APIBaseURL represents the base URL for the Meteologix API
// We currently support v02 of the API
const APIBaseURL = "https://api.kachelmannwetter.com/v02"
const (
// DefaultAcceptLang is the default language set for API requests
DefaultAcceptLang = "en"
// DefaultUserAgent is the default User-Agent presented by the HTTPClient
DefaultUserAgent = "go-meteologix v" + VERSION
)
// Client represents the Meteologix API Client
type Client struct {
// co represents the Config for the Client
co *Config
// hc references the HTTPClient of the Server
hc *HTTPClient
}
// Config represents the Client configuration settings
type Config struct {
// ak holds the (optional) API key for the API user authentication
ak string
// al hold the (optional) accept-language tag
al string
// pw holds the (optional) passowrd for the API user authentication
pw string
// ua represents an alternative User-Agent HTTP header string
ua string
// un holds the (optional) username for the API user authentication
un string
}
// Option represents a function that is used for setting/overriding Config options
type Option func(*Config)
// New returns a new Meteologix API Client
func New(o ...Option) *Client {
co := &Config{}
co.al = DefaultAcceptLang
co.ua = DefaultUserAgent
// Set/override Config options
for _, opt := range o {
if opt == nil {
continue
}
opt(co)
}
return &Client{
co: co,
hc: NewHTTPClient(co),
}
}
// WithAcceptLanguage sets the HTTP Accept-Lanauge header of the HTTP client
//
// The provided string needs to conform the HTTP Accept-Language header format
// See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language
func WithAcceptLanguage(l string) Option {
if l == "" {
return nil
}
return func(co *Config) {
co.al = l
}
}
// WithAPIKey sets the API Key for user authentication of the HTTP client
func WithAPIKey(k string) Option {
if k == "" {
return nil
}
return func(co *Config) {
co.ak = k
}
}
// WithPassword sets the HTTP Basic auth password for the HTTP client
func WithPassword(p string) Option {
if p == "" {
return nil
}
return func(co *Config) {
co.pw = p
}
}
// WithUserAgent sets a custom user agent string for the HTTP client
func WithUserAgent(a string) Option {
if a == "" {
return nil
}
return func(co *Config) {
co.ua = a
}
}
// WithUsername sets the HTTP Basic auth username for the HTTP client
func WithUsername(u string) Option {
if u == "" {
return nil
}
return func(co *Config) {
co.un = u
}
}