Skip to content

Instantly share code, notes, and snippets.

@SteveBate
Last active October 4, 2015 17:02
Show Gist options
  • Save SteveBate/5b175880b51f7986dfb6 to your computer and use it in GitHub Desktop.
Save SteveBate/5b175880b51f7986dfb6 to your computer and use it in GitHub Desktop.
Sample showing a request to Google's Places Webservice API to find addresses
package places
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
type PlaceRequest struct {
apikey string
format string
Result string
}
func New() *PlaceRequest {
return &PlaceRequest{
format: "xml",
apikey: "your api key",
}
}
func (p *PlaceRequest) Format(format string) {
switch format {
case "xml", "XML", "json", "JSON":
p.format = strings.ToLower(format)
default:
panic(errors.New(fmt.Sprintf("Invalid format: %s", format)))
}
}
func (p *PlaceRequest) Search(place string) error {
safePlace := url.QueryEscape(place)
url := fmt.Sprintf("https://maps.googleapis.com/maps/api/place/autocomplete/%s?input=%s&types=establishment&key=%s", p.format, safePlace, p.apikey)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
c := http.Client{}
resp, err := c.Do(req)
defer resp.Body.Close()
if err != nil {
return err
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
p.Result = string(data)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment