Skip to content

Commit

Permalink
Add default clients and package level functions
Browse files Browse the repository at this point in the history
  • Loading branch information
qba73 committed Apr 2, 2024
1 parent 2eea0b7 commit 58554ef
Show file tree
Hide file tree
Showing 14 changed files with 57 additions and 125 deletions.
24 changes: 8 additions & 16 deletions elevation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,8 @@ func TestGetElevationSRTM1ReturnsDataOnValidInput(t *testing.T) {
ts := newElevationTestServer(srtm1, wantReqURI, t)
defer ts.Close()

client, err := geonames.NewClient("DummyUser", geonames.WithBaseURL(ts.URL))
if err != nil {
t.Fatal(err)
}
client := geonames.NewClient("DummyUser")
client.BaseURL = ts.URL

want := geonames.Elevation{
Type: "srtm1",
Expand Down Expand Up @@ -66,10 +64,8 @@ func TestGetElevationSRTM3ReturnsDataOnValidInput(t *testing.T) {
ts := newElevationTestServer(srtm3, wantReqURI, t)
defer ts.Close()

client, err := geonames.NewClient("DummyUser", geonames.WithBaseURL(ts.URL))
if err != nil {
t.Fatal(err)
}
client := geonames.NewClient("DummyUser")
client.BaseURL = ts.URL

want := geonames.Elevation{
Type: "srtm3",
Expand Down Expand Up @@ -97,10 +93,8 @@ func TestGetElevationAstergdemReturnsDataOnValidInput(t *testing.T) {
ts := newElevationTestServer(astergdem, wantReqURI, t)
defer ts.Close()

client, err := geonames.NewClient("DummyUser", geonames.WithBaseURL(ts.URL))
if err != nil {
t.Fatal(err)
}
client := geonames.NewClient("DummyUser")
client.BaseURL = ts.URL

want := geonames.Elevation{
Type: "astergdem",
Expand Down Expand Up @@ -128,10 +122,8 @@ func TestGetElevationGTOPO30ReturnsDataOnValidInput(t *testing.T) {
ts := newElevationTestServer(gtopo30, wantReqURI, t)
defer ts.Close()

client, err := geonames.NewClient("DummyUser", geonames.WithBaseURL(ts.URL))
if err != nil {
t.Fatal(err)
}
client := geonames.NewClient("DummyUser")
client.BaseURL = ts.URL

want := geonames.Elevation{
Type: "gtopo30",
Expand Down
5 changes: 0 additions & 5 deletions examples/postal/go.mod

This file was deleted.

3 changes: 0 additions & 3 deletions examples/postal/go.sum

This file was deleted.

8 changes: 1 addition & 7 deletions examples/postal/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,13 @@ package main
import (
"fmt"
"log"
"os"

"github.com/qba73/geonames"
)

func main() {
// We exported valid "GEONAMES_USER" env var
geo, err := geonames.NewClient(os.Getenv("GEONAMES_USER"))
if err != nil {
panic(err)
}

codes, err := geo.GetPostCode("Fort William", "UK")
codes, err := geonames.GetPostCode("Fort William", "UK")
if err != nil {
log.Fatal(err)
}
Expand Down
5 changes: 0 additions & 5 deletions examples/wikipedia/go.mod

This file was deleted.

3 changes: 0 additions & 3 deletions examples/wikipedia/go.sum

This file was deleted.

8 changes: 1 addition & 7 deletions examples/wikipedia/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,13 @@ package main
import (
"fmt"
"log"
"os"

"github.com/qba73/geonames"
)

func main() {
// We exported valid "GEONAMES_USER" env var
geo, err := geonames.NewClient(os.Getenv("GEONAMES_USER"))
if err != nil {
panic(err)
}

codes, err := geo.GetPostCode("Fort William", "UK")
codes, err := geonames.GetPostCode("Fort William", "UK")
if err != nil {
log.Fatal(err)
}
Expand Down
87 changes: 27 additions & 60 deletions geonames.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,13 @@ package geonames
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"time"
)

const (
libraryVersion = "0.1"
userAgent = "geonames/" + libraryVersion
)

type option func(*Client) error

// WithHTTPClient configures the Geonames HTTP Client.
func WithHTTPClient(h *http.Client) option {
return func(c *Client) error {
if h == nil {
return errors.New("nil http Client")
}
c.HTTPClient = h
return nil
}
}

// WithBaseURL configures a base URL for the Geonames client.
func WithBaseURL(url string) option {
return func(c *Client) error {
if url == "" {
return errors.New("nil baseURL")
}
c.BaseURL = url
return nil
}
}

// WithHTTPHeader configures custom HTTP Headers used by the Geonames client.
func WithHTTPHeaders(header http.Header) option {
return func(c *Client) error {
if header == nil {
return errors.New("nil HTTP headers")
}
c.Headers = header
return nil
}
}

// Client holds data required for communicating with the Geonames Web Services.
type Client struct {
UserName string
Expand All @@ -61,24 +21,16 @@ type Client struct {
Headers map[string][]string
}

var DefaultClient = Client{
UserName: "demo",
BaseURL: "http://api.geonames.org",
HTTPClient: http.DefaultClient,
Headers: map[string][]string{"Content-Type": {"application/json"}},
}

// NewDemoClient creates a demo client. Demo client
// does not require username registration at geonames.org website.
func NewDemoClient() *Client {
return &DefaultClient
}
const (
libraryVersion = "0.1"
userAgent = "geonames/" + libraryVersion
)

// NewClient creates a new client for GeoNames Web service.
//
// The username has to be registered at the GeoNames.org website.
// HTTP requests without a valid username will return 403 HTTP errors.
func NewClient(username string, options ...option) (*Client, error) {
func NewClient(username string) *Client {
c := Client{
UserName: username,
UserAgent: userAgent,
Expand All @@ -91,12 +43,7 @@ func NewClient(username string, options ...option) (*Client, error) {
"Content-Type": {"application/json"},
},
}
for _, opt := range options {
if err := opt(&c); err != nil {
return nil, fmt.Errorf("creating geonames client: %w", err)
}
}
return &c, nil
return &c
}

func (c Client) get(ctx context.Context, url string, data any) error {
Expand Down Expand Up @@ -130,3 +77,23 @@ type Position struct {
Lat float64
Lng float64
}

var DemoClient = &Client{
UserName: "demo",
BaseURL: "http://api.geonames.org",
HTTPClient: http.DefaultClient,
Headers: map[string][]string{
"Content-Type": {"application/json"},
},
}

var ClientFromEnv = &Client{
UserName: os.Getenv("GEONAMES_USER"),
BaseURL: "http://api.geonames.org",
HTTPClient: &http.Client{
Timeout: 10 * time.Second,
},
Headers: map[string][]string{
"Content-Type": {"application/json"},
},
}
8 changes: 2 additions & 6 deletions geonames_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,6 @@ func TestWikipediaResolvesGeoNameOnValidInput(t *testing.T) {
defer ts.Close()

name, country := "Castlebar", "IE"
client, err := geonames.NewClient("DummyUser", geonames.WithBaseURL(ts.URL))
if err != nil {
t.Fatal(err)
}

client.GetPlace(context.Background(), name, country, 1)
c := geonames.NewClient("DummyUser")
c.GetPlace(context.Background(), name, country, 1)
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module github.com/qba73/geonames

go 1.21
go 1.22

require github.com/google/go-cmp v0.6.0
5 changes: 5 additions & 0 deletions postal.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,8 @@ func (c Client) buildPostalURL(placeName, countryCode string) (string, error) {
u.RawQuery = params.Encode()
return u.String(), nil
}

// GetPostalCode takes place and country and returns postal codes.
func GetPostCode(place, country string) ([]PostalCode, error) {
return ClientFromEnv.GetPostCode(context.Background(), place, country)
}
12 changes: 4 additions & 8 deletions postal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,8 @@ func TestGetPostalCodes_ReturnsSingleValueOnValidInput(t *testing.T) {
)
defer ts.Close()

client, err := geonames.NewClient("DummyUser", geonames.WithBaseURL(ts.URL))
if err != nil {
t.Fatal(err)
}
client := geonames.NewClient("DummyUser")
client.BaseURL = ts.URL

place, country := "Castlebar", "IE"
got, err := client.GetPostCode(context.Background(), place, country)
Expand Down Expand Up @@ -63,10 +61,8 @@ func TestGetPostalCodes_ReturnsMultipleValuesOnValidInput(t *testing.T) {
)
defer ts.Close()

client, err := geonames.NewClient("DummyUser", geonames.WithBaseURL(ts.URL))
if err != nil {
t.Fatal(err)
}
client := geonames.NewClient("DummyUser")
client.BaseURL = ts.URL

place, country := "Dublin", "IE"
got, err := client.GetPostCode(context.Background(), place, country)
Expand Down
6 changes: 6 additions & 0 deletions wikipedia.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,9 @@ func (c Client) buildWikiURL(place, country string, maxResults int) (string, err
u.RawQuery = params.Encode()
return u.String(), nil
}

// GetPlace takes place name, country and max results and returns
// a list of names associated with the place.
func GetPlace(name, country string, maxResults int) ([]Geoname, error) {
return ClientFromEnv.GetPlace(context.Background(), name, country, maxResults)
}
6 changes: 2 additions & 4 deletions wikipedia_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@ func TestGetPlace_RetrievesSingleGeoNameOnValidInput(t *testing.T) {
ts := newTestServer(testFile, wantReqURI, t)
defer ts.Close()

client, err := geonames.NewClient("DummyUser", geonames.WithBaseURL(ts.URL))
if err != nil {
t.Fatal(err)
}
client := geonames.NewClient("DummyUser")
client.BaseURL = ts.URL

name := "Castlebar"
country := "IE"
Expand Down

0 comments on commit 58554ef

Please sign in to comment.