Debian Codegraph @

examples/yelp/main.go

raw symbols SCIP
1 // Copyright 2015 Gary Burd
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"): you may
4 // not use this file except in compliance with the License. You may obtain
5 // a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations
13 // under the License.
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 }