use_urlshortener.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // use_urlshortener.go
  2. package main
  3. import (
  4. urlshortener "code.google.com/p/google-api-go-client/urlshortener/v1"
  5. "fmt"
  6. "net/http"
  7. "text/template"
  8. )
  9. func main() {
  10. http.HandleFunc("/", root)
  11. http.HandleFunc("/short", short)
  12. http.HandleFunc("/long", long)
  13. http.ListenAndServe("localhost:8080", nil)
  14. }
  15. // the template used to show the forms and the results web page to the user
  16. var rootHtmlTmpl = template.Must(template.New("rootHtml").Parse(`
  17. <html><body>
  18. <h1>URL SHORTENER</h1>
  19. {{if .}}{{.}}<br /><br />{{end}}
  20. <form action="/short" type="POST">
  21. Shorten this: <input type="text" name="longUrl" />
  22. <input type="submit" value="Give me the short URL" />
  23. </form>
  24. <br />
  25. <form action="/long" type="POST">
  26. Expand this: http://goo.gl/<input type="text" name="shortUrl" />
  27. <input type="submit" value="Give me the long URL" />
  28. </form>
  29. </body></html>
  30. `))
  31. func root(w http.ResponseWriter, r *http.Request) {
  32. rootHtmlTmpl.Execute(w, nil)
  33. }
  34. func short(w http.ResponseWriter, r *http.Request) {
  35. longUrl := r.FormValue("longUrl")
  36. urlshortenerSvc, _ := urlshortener.New(http.DefaultClient)
  37. url, _ := urlshortenerSvc.Url.Insert(&urlshortener.Url{LongUrl: longUrl}).Do()
  38. rootHtmlTmpl.Execute(w, fmt.Sprintf("Shortened version of %s is : %s", longUrl, url.Id))
  39. }
  40. func long(w http.ResponseWriter, r *http.Request) {
  41. shortUrl := "http://goo.gl/" + r.FormValue("shortUrl")
  42. urlshortenerSvc, _ := urlshortener.New(http.DefaultClient)
  43. url, err := urlshortenerSvc.Url.Get(shortUrl).Do()
  44. if err != nil {
  45. fmt.Println("error: %v", err)
  46. return
  47. }
  48. rootHtmlTmpl.Execute(w, fmt.Sprintf("Longer version of %s is : %s", shortUrl, url.LongUrl))
  49. }