1. Reference URL: https://github.com/unknwon/the-way-to-go_zh_en/blob/master/ebook/09.11.md . Test by browsing the page of http://localhost:8080/. Enter: http://www.destandaard.be in shorten this, and click: Give me the short URL. Loading until timeout. as shown in Figure 1
Figure 1
2. Check the terminal output and report an error: Runtime Error: Invalid memory address or nil pointer dereference. as shown in Figure 2
Figure 2
3. Check the Go file, urlshortener.go. For the simplicity of the code, we do not detect the returned error status, but we must do the detection in the application of the real production environment. Open the URL: http://goo.gl and find that by March 30, 2019, the URL shortener API has stopped supporting. as shown in Figure 3
Figure 3
package main
import (
"fmt"
"net/http"
"text/template"
"google.golang.org/api/urlshortener/v1"
)
func main() {
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 user
var 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>
`))
func root(w http.ResponseWriter, r *http.Request) {
rootHtmlTmpl.Execute(w, nil)
}
func short(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))
}
func long(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))
}
4. For developers who want to migrate to FDL, please refer to our migration guide. Click the link: Our Migration Guide. Change to use Firebase dynamic links instead of using URL shortener. as shown in Figure 4
Figure 4
Leave a Reply