This repository has been archived on 2022-08-17. You can view files and clone it, but cannot push or open issues or pull requests.
dex/vendor/google.golang.org/api/examples/urlshortener.go
2016-04-08 11:56:29 -07:00

46 lines
1.1 KiB
Go

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, _ := urlshortener.New(client)
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)
}