From 70a0403b6d3a167c4101cbe884fab83a05227c05 Mon Sep 17 00:00:00 2001 From: Jason Hall Date: Thu, 5 Mar 2015 13:36:26 -0500 Subject: [PATCH] Proactively fail if SnapToRoads is called without an API key --- maps_test.go | 12 ++++++++---- roads.go | 7 +++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/maps_test.go b/maps_test.go index 346f9b8..ee44709 100644 --- a/maps_test.go +++ b/maps_test.go @@ -11,7 +11,7 @@ import ( var ( apiKey = flag.String("apiKey", "", "Google Maps API key") - ctx = NewContext("key", &http.Client{}) + ctx = NewContext("", &http.Client{}) wctx = NewWorkContext("clientID", "privKey", &http.Client{}) ) @@ -184,8 +184,6 @@ func TestDistanceMatrix(t *testing.T) { } func TestSnapToRoads(t *testing.T) { - ctx = NewContext(*apiKey, &http.Client{}) - path := []LatLng{{-35.27801, 149.12958}, {-35.28032, 149.12907}, {-35.28099, 149.12929}, @@ -197,7 +195,13 @@ func TestSnapToRoads(t *testing.T) { opts := &SnapToRoadsOpts{ Interpolate: true, } - r, err := SnapToRoads(ctx, path, opts) + + if _, err := SnapToRoads(ctx, path, opts); err != ErrNoAPIKey { + t.Errorf("unexpected error, got %v, want %v", err, ErrNoAPIKey) + } + + keyCtx := NewContext(*apiKey, &http.Client{}) + r, err := SnapToRoads(keyCtx, path, opts) if err != nil { t.Errorf("unexpected error: %v", err) } diff --git a/roads.go b/roads.go index d06de9c..0f163f8 100644 --- a/roads.go +++ b/roads.go @@ -1,6 +1,7 @@ package maps import ( + "errors" "net/url" "code.google.com/p/go.net/context" @@ -8,7 +9,13 @@ import ( const roadsAPIBaseURL = "https://roads.googleapis.com/v1/" +var ErrNoAPIKey = errors.New("must provide an API key") + func SnapToRoads(ctx context.Context, path []LatLng, opts *SnapToRoadsOpts) ([]SnappedPoint, error) { + if key(ctx) == "" { + return nil, ErrNoAPIKey + } + var d snapToRoadsResponse if err := doDecode(ctx, roadsAPIBaseURL+snapToRoads(path, opts), &d); err != nil { return nil, err