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.
 
 
 

65 lines
1.7 KiB

  1. // Copyright 2017 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain 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,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "log"
  18. "net/http"
  19. "os"
  20. "strings"
  21. urlshortener "google.golang.org/api/urlshortener/v1"
  22. )
  23. func init() {
  24. registerDemo("urlshortener", urlshortener.UrlshortenerScope, urlShortenerMain)
  25. }
  26. func urlShortenerMain(client *http.Client, argv []string) {
  27. if len(argv) != 1 {
  28. fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx (to look up details)\n")
  29. fmt.Fprintf(os.Stderr, " urlshortener http://example.com/long (to shorten)\n")
  30. return
  31. }
  32. svc, err := urlshortener.New(client)
  33. if err != nil {
  34. log.Fatalf("Unable to create UrlShortener service: %v", err)
  35. }
  36. urlstr := argv[0]
  37. // short -> long
  38. if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
  39. url, err := svc.Url.Get(urlstr).Do()
  40. if err != nil {
  41. log.Fatalf("URL Get: %v", err)
  42. }
  43. fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
  44. return
  45. }
  46. // long -> short
  47. url, err := svc.Url.Insert(&urlshortener.Url{
  48. Kind: "urlshortener#url", // Not really needed
  49. LongUrl: urlstr,
  50. }).Do()
  51. if err != nil {
  52. log.Fatalf("URL Insert: %v", err)
  53. }
  54. fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
  55. }