0

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)
}
4
  • 3
    The fragment (everything after the #) is not transmitted to the server. You'll have pick a different approach. Commented Aug 24, 2018 at 0:15
  • What does this have to do with my question? I am only interested in redirecting the exact url of "localhost:9000/". Whether or not I use a hash in the url to redirect to shouldn't make a difference should it? Commented Aug 24, 2018 at 2:22
  • 1
    @cookiekid, you cannot tell the difference between / and /#/trade/gem/GEM on the server; they both look like /, hence the redirect loop. The fragment is for client-side use only (i.e. JavaScript). Commented Aug 24, 2018 at 5:56
  • Oh ok. Thanks. So I have to do the redirect on the frontend then. I think React Router has a tool for that anyway. Commented Aug 25, 2018 at 17:13

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.