Whenever a request is made from localhost:9000/ I want to redirect the user to localhost:9000/#/trade/gem/GEM . The problem I am getting is that I get infinite redirects because "/" preceeds every url. How do I make it so that the user is only redirected if they visit the exact url of localhost:9000/ ? My code is below:
var newUrl string = "/#/trade/gem/GEM"
func handleRedirect(rw http.ResponseWriter, req *http.Request) {
http.Redirect(rw, req, newUrl, http.StatusSeeOther)
}
func main() {
http.Handle("/#/trade/", fs)
http.HandleFunc("/", handleRedirect) //This is the exact url I want to redirect from
http.ListenAndServe(":9000", nil)
}
When the /
is registered then all the url will redirect to this until the other pattern is not registered.To solve this and handling only specific patterns you can write a custom handler and you can implement a logic where it redirects to the specific url whenever the localhost:9000/
is opened.
package main
import (
"fmt"
"net/http"
)
type Handler struct{}
var NewUrl string = "/trade/gem/GEM"
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
uri := r.URL.Path
if uri == "/" {
http.Redirect(w, r, NewUrl, http.StatusSeeOther)
}
fmt.Fprintf(w, uri)
return
}
func main() {
handler := new(Handler)
http.ListenAndServe(":9000", handler)
}
For more details check http.handler
Note: You can not use #
in the uri.