Skip to content

Instantly share code, notes, and snippets.

@xlab
Last active June 21, 2017 18:52
Show Gist options
  • Select an option

  • Save xlab/7ee554900523e58c52e0 to your computer and use it in GitHub Desktop.

Select an option

Save xlab/7ee554900523e58c52e0 to your computer and use it in GitHub Desktop.
Example of calling the Google's Merchant API (content scope) from Go lang.
// Package products is an example of calling the Google's Merchant API (content scope) from Go lang.
package products
import (
"strconv"
"code.google.com/p/goauth2/oauth"
"code.google.com/p/google-api-go-client/content/v2"
)
// Product represents a Google Merchant product.
type Product struct {
ID string
Name string
ImageURL string
LocationURL string
Price float32
Currency string
Type string
}
// Fetcher stores the state and keys.
type Fetcher struct {
config *oauth.Config
transport *oauth.Transport
svc *content.Service
}
// Config represents the credentials used for OAuth2 authorization.
type Config struct {
AccessToken string
ClientId string
ClientSecret string
}
// NewFetcher returns a new fetcher supplied with credentials.
func NewFetcher(cfg *Config) (f *Fetcher, err error) {
f = &Fetcher{}
f.config = &oauth.Config{
ClientId: cfg.ClientId,
ClientSecret: cfg.ClientSecret,
Scope: content.ContentScope,
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
f.transport = &oauth.Transport{
Config: f.config,
Token: &oauth.Token{AccessToken: cfg.AccessToken},
}
f.svc, err = content.New(f.transport.Client())
return
}
// Fetch fetches all products from the given merchant's account. You should create a
// productChan with sufficient size, otherwise this method will block.
func (f *Fetcher) Fetch(merchantId uint64, productChan chan<- *Product) (err error) {
var list *content.ProductsListResponse
if list, err = f.svc.Products.List(merchantId).Do(); err != nil {
return
}
for _, res := range list.Resources {
p := &Product{}
p.ID = res.Id
p.ImageURL = res.ImageLink
p.LocationURL = res.Link
p.Name = res.Title
p.Currency = res.Price.Currency
p.Type = "photo"
var price float64
if price, err = strconv.ParseFloat(res.Price.Value, 32); err != nil {
return
}
p.Price = float32(price)
productChan <- p
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment