...

Source file src/google.golang.org/api/examples/urlshortener.go

Documentation: google.golang.org/api/examples

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

View as plain text