Rhymen / go-whatsapp

WhatsApp Web API
MIT License
2.05k stars 490 forks source link

How to redirect after login successful ? #562

Open gampangdibaca opened 3 years ago

gampangdibaca commented 3 years ago

My program is already working, but i want to redirect the page to home after scanning qr and login process is finished.

Here is part of my code :

func loginWhatsapp(w http.ResponseWriter, req *http.Request){
    session, err := whatsappWeb.ReadSession()
    if err == nil {
        err := tpl.ExecuteTemplate(w, "whatsapp-login.gohtml", "")
        if err != nil {
            log.Fatalln(err)
        }
        return
    } else {
        channel := make(chan string)
        go func() {
            conn, err := whatsapp.NewConn(15 * time.Second)
            session, err = conn.Login(channel)
            if err != nil {
                log.Print("Error during restoreSession ", err)
                return
            }
            log.Print("Session", session)
            //save session
            err = whatsappWeb.WriteSession(session)
            if err != nil {
                fmt.Errorf("error saving session: %v\n", err)
            }
            conn.GetConnected()
            log.Println("login finish")
        }()
        log.Print("Waiting for QR Generation")
        qrData := <-channel
        image, _ := qrcode.Encode(qrData, qrcode.Medium, 256)
        log.Print("QR Generated")
        w.Header().Set("Content-Type", "image/png")
        w.Header().Set("Content-Length", strconv.Itoa(len(image)))
        if _, err := w.Write(image); err != nil {
            log.Println("unable to write image.")
        }
        log.Println("login finished")
        http.Redirect(w, req, "/", http.StatusSeeOther)
    }

}

i have already tried using channel and waitgroup. but it is blocking the qr from getting shown on the screen. If anyone can help, that would be so much appreciated.

danielspk commented 3 years ago

Hi @gampangdibaca.

You must return the QR image using an http response. When the image is correctly scanned you must notify the client of this operation, you can do it through a websocket or SSE (see the Mercure Hub project).

I don't see an easy way to solve it.

akbarfa49 commented 3 years ago

@gampangdibaca i think u should add wg.wait or channel before http.redirect.

wa connect -> login finish -> signaling the wg.wait or channel -> continue http redirect.