~nskaggs/+junk/xenial-test

« back to all changes in this revision

Viewing changes to src/google.golang.org/api/examples/urlshortener.go

  • Committer: Nicholas Skaggs
  • Date: 2016-10-24 20:56:05 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161024205605-z8lta0uvuhtxwzwl
Initi with beta15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package main
 
2
 
 
3
import (
 
4
        "fmt"
 
5
        "log"
 
6
        "net/http"
 
7
        "os"
 
8
        "strings"
 
9
 
 
10
        urlshortener "google.golang.org/api/urlshortener/v1"
 
11
)
 
12
 
 
13
func init() {
 
14
        registerDemo("urlshortener", urlshortener.UrlshortenerScope, urlShortenerMain)
 
15
}
 
16
 
 
17
func urlShortenerMain(client *http.Client, argv []string) {
 
18
        if len(argv) != 1 {
 
19
                fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx     (to look up details)\n")
 
20
                fmt.Fprintf(os.Stderr, "       urlshortener http://example.com/long (to shorten)\n")
 
21
                return
 
22
        }
 
23
 
 
24
        svc, _ := urlshortener.New(client)
 
25
        urlstr := argv[0]
 
26
 
 
27
        // short -> long
 
28
        if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
 
29
                url, err := svc.Url.Get(urlstr).Do()
 
30
                if err != nil {
 
31
                        log.Fatalf("URL Get: %v", err)
 
32
                }
 
33
                fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
 
34
                return
 
35
        }
 
36
 
 
37
        // long -> short
 
38
        url, err := svc.Url.Insert(&urlshortener.Url{
 
39
                Kind:    "urlshortener#url", // Not really needed
 
40
                LongUrl: urlstr,
 
41
        }).Do()
 
42
        if err != nil {
 
43
                log.Fatalf("URL Insert: %v", err)
 
44
        }
 
45
        fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
 
46
}