1// Copyright 2017 Google Inc. All Rights Reserved.
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
15package main
16
17import (
18	"fmt"
19	"log"
20	"net/http"
21	"os"
22	"strings"
23
24	urlshortener "google.golang.org/api/urlshortener/v1"
25)
26
27func init() {
28	registerDemo("urlshortener", urlshortener.UrlshortenerScope, urlShortenerMain)
29}
30
31func urlShortenerMain(client *http.Client, argv []string) {
32	if len(argv) != 1 {
33		fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx     (to look up details)\n")
34		fmt.Fprintf(os.Stderr, "       urlshortener http://example.com/long (to shorten)\n")
35		return
36	}
37
38	svc, err := urlshortener.New(client)
39	if err != nil {
40		log.Fatalf("Unable to create UrlShortener service: %v", err)
41	}
42
43	urlstr := argv[0]
44
45	// short -> long
46	if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
47		url, err := svc.Url.Get(urlstr).Do()
48		if err != nil {
49			log.Fatalf("URL Get: %v", err)
50		}
51		fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
52		return
53	}
54
55	// long -> short
56	url, err := svc.Url.Insert(&urlshortener.Url{
57		Kind:    "urlshortener#url", // Not really needed
58		LongUrl: urlstr,
59	}).Do()
60	if err != nil {
61		log.Fatalf("URL Insert: %v", err)
62	}
63	fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
64}
65