转到Golang中间件内部的新页面

Let's say I have a button which will open a new page. This button's action is handled by an AJAX call to Golang API. This Golang API is wrapped by a middleware, Verify, which will verify everything before directing to that page. The page defined in the function passed into the middleware is using Golang HTML template.

router.GET("/newpage", Verify(newpageHandler))

func Verify(h http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {

        //verify everything here
        //if all verify, call newpageHandler to redirect to new page
        h.ServeHTTP(w,r)
    }
}

func newpageHandler(w http.ResponseWriter, r *http.Request) {
    //this handler will process the html template
}

When I click the button (AJAX call to the /newpage), it doesn't open the new page, but only returns the HTML content from newpageHandler handler. I can see the HTML returned from the browser's developer tools, but it doesn't get that new page defined in newpageHandler.

Is it okay to use http.Redirect?

If you will to change the page, then AJAX isn't what you want. Instead of sending an AJAX request to the API, you should redirect the browser to that API using one of the following methods for example:

HTML :

<a href="url/to/my/api">Go To page</a>

Javascript:

window.location = "url/to/my/api"

AJAX calls will follow redirects implicitly. Alas, there is no way to prevent that. So, using http.Redirect is not a good option.

You could signal in your Verify func if the request was accepted or not. This can be easily done with http status codes. If everything was all right, you could return a 2xx code. In case of some error, you could return a 4xx code.

func Verify(h http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {

        //verify everything here. verifcationFunc() returns a bool
        if verifcationFunc() {
          w.WriteHeader(http.StatusOK)
        } else {
          w.WriteHeader(http.StatusUnauthorized)
        }
    }
}

You can now evaluate the returned status code in your JavaScript. On a 200 you can set the new location in JavaScript. This can be done with window.location. On a 401 code (in the example above) you can output an error message.