| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package main |
| 16 |
|
| 17 |
import ( |
| 18 |
"encoding/json" |
| 19 |
"flag" |
| 20 |
"fmt" |
| 21 |
"io/ioutil" |
| 22 |
"log" |
| 23 |
"net/url" |
| 24 |
|
| 25 |
"github.com/gomodule/oauth1/oauth" |
| 26 |
) |
| 27 |
|
| 28 |
type client struct { |
| 29 |
client oauth.Client |
| 30 |
token oauth.Credentials |
| 31 |
} |
| 32 |
|
| 33 |
func (c *client) get(urlStr string, params url.Values, v interface{}) error { |
| 34 |
resp, err := c.client.Get(nil, &c.token, urlStr, params) |
| 35 |
if err != nil { |
| 36 |
return err |
| 37 |
} |
| 38 |
defer resp.Body.Close() |
| 39 |
if resp.StatusCode != 200 { |
| 40 |
return fmt.Errorf("yelp status %d", resp.StatusCode) |
| 41 |
} |
| 42 |
return json.NewDecoder(resp.Body).Decode(v) |
| 43 |
} |
| 44 |
|
| 45 |
var credPath = flag.String("config", "config.json", "Path to configuration file containing the application's credentials.") |
| 46 |
|
| 47 |
func readCredentials(c *client) error { |
| 48 |
b, err := ioutil.ReadFile(*credPath) |
| 49 |
if err != nil { |
| 50 |
return err |
| 51 |
} |
| 52 |
var creds struct { |
| 53 |
ConsumerKey string |
| 54 |
ConsumerSecret string |
| 55 |
Token string |
| 56 |
TokenSecret string |
| 57 |
} |
| 58 |
if err := json.Unmarshal(b, &creds); err != nil { |
| 59 |
return err |
| 60 |
} |
| 61 |
c.client.Credentials.Token = creds.ConsumerKey |
| 62 |
c.client.Credentials.Secret = creds.ConsumerSecret |
| 63 |
c.token.Token = creds.Token |
| 64 |
c.token.Secret = creds.TokenSecret |
| 65 |
return nil |
| 66 |
} |
| 67 |
|
| 68 |
func main() { |
| 69 |
var c client |
| 70 |
if err := readCredentials(&c); err != nil { |
| 71 |
log.Fatal(err) |
| 72 |
} |
| 73 |
|
| 74 |
var data struct { |
| 75 |
Businesses []struct { |
| 76 |
Name string |
| 77 |
Location struct { |
| 78 |
DisplayAddress []string `json:"display_address"` |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
form := url.Values{"term": {"food"}, "location": {"San Francisco"}} |
| 83 |
if err := c.get("http://api.yelp.com/v2/search", form, &data); err != nil { |
| 84 |
log.Fatal(err) |
| 85 |
} |
| 86 |
|
| 87 |
for _, b := range data.Businesses { |
| 88 |
addr := "" |
| 89 |
if len(b.Location.DisplayAddress) > 0 { |
| 90 |
addr = b.Location.DisplayAddress[0] |
| 91 |
} |
| 92 |
log.Println(b.Name, addr) |
| 93 |
} |
| 94 |
} |