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) }
func handleShorten(w http.ResponseWriter, r *http.Request) { longUrl := r.FormValue("longUrl") //get the value of the text field with the name longUrl in the form urlshortenerSvc, _ := urlshortener.New(http.DefaultFClient) //use the default client that is available in the http package and create a new instance of the url shortener service url, _ := urlshortenerSvc.Insert(&urlshortener.Url {LongUrl: longUrl}).Do() //fill in the Url data structure with the given long url and call the service rootHtmlTmpl.Execute(w, fmt.Sprintf("Shortened version of `%s` is: %s", longUrl, url.Id)) }