packagemainimport ("fmt""net/http""text/template""google.golang.org/api/urlshortener/v1")funcmain() { http.HandleFunc("/", root) http.HandleFunc("/short", short) http.HandleFunc("/long", long) http.ListenAndServe("localhost:8080", nil)}// the template used to show the forms and the results web page to the uservar rootHtmlTmpl = template.Must(template.New("rootHtml").Parse(`<html><body><h1>URL SHORTENER</h1>{{if .}}{{.}}<br /><br />{{end}}<form action="/short" type="POST">Shorten this: <input type="text" name="longUrl" /><input type="submit" value="Give me the short URL" /></form><br /><form action="/long" type="POST">Expand this: http://goo.gl/<input type="text" name="shortUrl" /><input type="submit" value="Give me the long URL" /></form></body></html>`))funcroot(w http.ResponseWriter, r *http.Request) { rootHtmlTmpl.Execute(w, nil)}funcshort(w http.ResponseWriter, r *http.Request) { longUrl := r.FormValue("longUrl") urlshortenerSvc, _ := urlshortener.New(http.DefaultClient) url, _ := urlshortenerSvc.Url.Insert(&urlshortener.Url{LongUrl: longUrl,}).Do() rootHtmlTmpl.Execute(w, fmt.Sprintf("Shortened version of %s is : %s", longUrl, url.Id))}funclong(w http.ResponseWriter, r *http.Request) { shortUrl :="http://goo.gl/"+ r.FormValue("shortUrl") urlshortenerSvc, _ := urlshortener.New(http.DefaultClient) url, err := urlshortenerSvc.Url.Get(shortUrl).Do()if err !=nil { fmt.Println("error: %v", err)return } rootHtmlTmpl.Execute(w, fmt.Sprintf("Longer version of %s is : %s", shortUrl, url.LongUrl))}
执行这段代码:
go run urlshortener.go
通过浏览 http://localhost:8080/ 的页面来测试。
为了代码的简洁我们并没有检测返回的错误状态,但是在真实的生产环境的应用中一定要做检测。
将应用放入 Google App Engine,我们只需要在之前的代码中作出如下改变:
package main -> package urlshort
func main() -> func init()