You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

78 lines
2.1 KiB

  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "os"
  10. "strconv"
  11. "strings"
  12. books "google.golang.org/api/books/v1"
  13. "google.golang.org/api/googleapi"
  14. )
  15. func init() {
  16. registerDemo("books", books.BooksScope, booksMain)
  17. }
  18. // booksMain is an example that demonstrates calling the Books API.
  19. //
  20. // Example usage:
  21. // go build -o go-api-demo *.go
  22. // go-api-demo -clientid="my-clientid" -secret="my-secret" books
  23. func booksMain(client *http.Client, argv []string) {
  24. if len(argv) != 0 {
  25. fmt.Fprintln(os.Stderr, "Usage: books")
  26. return
  27. }
  28. svc, err := books.New(client)
  29. if err != nil {
  30. log.Fatalf("Unable to create Books service: %v", err)
  31. }
  32. bs, err := svc.Mylibrary.Bookshelves.List().Do()
  33. if err != nil {
  34. log.Fatalf("Unable to retrieve mylibrary bookshelves: %v", err)
  35. }
  36. if len(bs.Items) == 0 {
  37. log.Fatal("You have no bookshelves to explore.")
  38. }
  39. for _, b := range bs.Items {
  40. // Note that sometimes VolumeCount is not populated, so it may erroneously say '0'.
  41. log.Printf("You have %v books on bookshelf %q:", b.VolumeCount, b.Title)
  42. // List the volumes on this shelf.
  43. vol, err := svc.Mylibrary.Bookshelves.Volumes.List(strconv.FormatInt(b.Id, 10)).Do()
  44. if err != nil {
  45. log.Fatalf("Unable to retrieve mylibrary bookshelf volumes: %v", err)
  46. }
  47. for _, v := range vol.Items {
  48. var info struct {
  49. Text bool `json:"text"`
  50. Image bool `json:"image"`
  51. }
  52. // Parse the additional fields, but ignore errors, as the information is not critical.
  53. googleapi.ConvertVariant(v.VolumeInfo.ReadingModes.(map[string]interface{}), &info)
  54. var s []string
  55. if info.Text {
  56. s = append(s, "text")
  57. }
  58. if info.Image {
  59. s = append(s, "image")
  60. }
  61. extra := fmt.Sprintf("; formats: %v", s)
  62. if v.VolumeInfo.ImageLinks != nil {
  63. extra += fmt.Sprintf("; thumbnail: %v", v.VolumeInfo.ImageLinks.Thumbnail)
  64. }
  65. log.Printf(" %q by %v%v", v.VolumeInfo.Title, strings.Join(v.VolumeInfo.Authors, ", "), extra)
  66. }
  67. }
  68. }