-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
urlshortener.go
54 lines (45 loc) · 1.28 KB
/
urlshortener.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright 2017 Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
urlshortener "google.golang.org/api/urlshortener/v1"
)
func init() {
registerDemo("urlshortener", urlshortener.UrlshortenerScope, urlShortenerMain)
}
func urlShortenerMain(client *http.Client, argv []string) {
if len(argv) != 1 {
fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx (to look up details)\n")
fmt.Fprintf(os.Stderr, " urlshortener http://example.com/long (to shorten)\n")
return
}
svc, err := urlshortener.New(client)
if err != nil {
log.Fatalf("Unable to create UrlShortener service: %v", err)
}
urlstr := argv[0]
// short -> long
if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
url, err := svc.Url.Get(urlstr).Do()
if err != nil {
log.Fatalf("URL Get: %v", err)
}
fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
return
}
// long -> short
url, err := svc.Url.Insert(&urlshortener.Url{
Kind: "urlshortener#url", // Not really needed
LongUrl: urlstr,
}).Do()
if err != nil {
log.Fatalf("URL Insert: %v", err)
}
fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
}