I have a GorrilaMux set up in Go that will make an API call if type in a specific URL in a browser. I want to make the same API call in my main method in go if the URL is given as a command line argument. However, the http.redirect() method which seems to be able to do this, requires a HTTP ResponseWriter and a *HTTPRequest variables as function parameters. I do not know how to produce these variables within a main method. How do I do this, OR, is there a better way to make the API call from the URL in Golang?
Code to set up Router
func main(){
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes { //Sets up predefined routes
router.
Path(route.Path).
Name(route.Name).
Handler(route.HandlerFunc)
}
URL:="localhost:8080/whatever" //URL I want to redirect, route would be "/whatever"
http.redirect(????)
}
An HTTP redirect is a response to a client and should be called from an invocation of a handler. The http.redirect(w http.ResponseWriter, r *http.Request)
function has no meaning in the context of the main function.
You can register a handler for the given route like so:
router.Path("/whatever").Handler(func(writer http.ResponseWriter, req *http.Request) {
http.Redirect(writer, req, "localhost:8080/whatever", http.StatusMovedPermanently)
))
This adds a path to the router and invokes the simple http.Handlerfunc
which contains a call to http.Redirect(...)
. Here this makes sense because we are handling a response to a client connection. It is logical to return a 301 status code and the URL for the target of the redirect.