Home > Mobile >  How to display a message on the DOM and redirect to a website at the same time in Go?
How to display a message on the DOM and redirect to a website at the same time in Go?

Time:01-15

I'm trying to display a message on the DOM and then redirect the user to a website, but only one would work.

Relevant code:

func main() {
    path, _ := filepath.Abs(os.Args[1])
    app := App{
        Auth:         somePackage.someMethod(many params),
        LibPath: path,
    }
    url := app.Auth.AuthURL(state)
    browser.OpenURL(url)

    mux := http.NewServeMux()
    mux.HandleFunc("/callback", app.CallbackHandler)
    if err := http.ListenAndServe("localhost:3000", mux); err != nil {
        log.Fatalf("Failed to start the server: %v", err)
    }
}


func (app *App) CallbackHandler(w http.ResponseWriter, r *http.Request) {
    token, err := app.Auth.Token(state, r)
    if err != nil {
        log.Print(err)
        http.Error(w, "Couldn't get token", http.StatusNotFound)
        return
    }

    app.Client = app.Auth.NewClient(token)

    app.someFunc()

    // w.Write([]byte("successful, Please check your dashboard"))
    http.Redirect(w, r, "https://someweb.site/dashboard/", http.StatusSeeOther)

    log.Print("done")
}

only one thing works, either w.Write([]byte("successful, Please check your dashboard")) or http.Redirect(w, r, "https://someweb.site/dashboard/", http.StatusSeeOther).

When both are used, the page (localhost:3000:....) shows:

successful, Please check your dashboard !a href="https://someweb.site/dashboard/">See Other</a! (i put ! to show it in markdown)

There are no errors in the functioning of the application, runs as it is expected to and does the job.

What is the issue and how to solve it?

CodePudding user response:

You cannot instruct the browser to go to another site and at the same time display the previous site. A browser can do these things only one after the other. So typically the HTML content is displayed and through some timer it will automatically move to the new site after a short time. This could be implemented with Javascript but also with a simple meta tag:

<meta http-equiv="refresh" content="5;url=https://example.com/" />
This content is displayed for 5 seconds, before it will redirect to example.com
  • Related