Hub
Menu
Sub navigation

Add Redirect code

As Go Web server is not using Apache and therefore not using the “. htaccess” file, you must do your own redirects in Go. I can think of three redirects.

  1. Static files like sitemap.xml and robots.txt.
  2. Redirect historically deleted pages.
  3. Show a 404 page if the page does not exist at all.

In a separate Go file I put all the redirects, as it can grow to be rather big if you have cleaned your site and got many old paths.

func redirect(w http.ResponseWriter, r *http.Request) {
  path := strings.Trim(r.URL.Path, "/")
  switch path {
  case "topnav", "sidenav":
    http.Redirect(w, r, "/navigation", http.StatusMovedPermanently)
  case "staticfiles":
    http.Redirect(w, r, "/robots", http.StatusMovedPermanently)
  case "go":
    http.Redirect(w, r, "/golang", http.StatusMovedPermanently)
  //notfound
  default:
    w.WriteHeader(http.StatusNotFound)
    tpl.ExecuteTemplate(w, "notfound.html", "")
    log("404: " + path)
  }
}