lundi 10 mai 2021

How to redirect to different route in golang

    package main

import (
    "database/sql"
    "fmt"
    "log"
    "net/http"

    _ "github.com/go-sql-driver/mysql"
)

//---------------------------------------------------index handler---------------------------------------------
func Index(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./templates/main.html")
    auser := r.FormValue("auser")
    apass := r.FormValue("apass")

    check := check(auser, apass)
    if check {
        http.Redirect(w, r, "/main/login", 200)
    } else {
        fmt.Fprintf(w, "USER NOT FOUND\n")
        fmt.Printf("USER NOT FOUND\n")
        http.Redirect(w, r, "/", http.StatusFound)
    }
}

func check(mail string, pass string) bool {
    status := false
    db, err := sql.Open("mysql", "root:yes@tcp(localhost:3306)/test_schema")

    if err != nil {
        fmt.Printf("not connected")
    }

    defer db.Close()

    query := "SELECT Passwords FROM test_schema.database WHERE Email ='" + mail + "'"
    res, err := db.Query(query)

    if err != nil {
        panic(err.Error())
    }
    for res.Next() {
        var name string
        if err := res.Scan(&name); err != nil {
            log.Fatal(err)
        }
        if name == pass {
            status = true
        }
    }
    if err := res.Err(); err != nil {
        log.Fatal(err)
    }
    return status
}

//---------------------------------------------------------------main----------------------------------------------------------
func main() {
    fileServer := http.FileServer(http.Dir("./templates"))
    http.Handle("/", fileServer)
    http.HandleFunc("/login", Index)
    http.HandleFunc("/main/login", Index)
    http.HandleFunc("/hospital/login", Index)
    log.Println("Server listening on :8080...")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal(err)
    }
}

The program opens index page correctly but when logged in it still opens the login page even when user is not registered. I created an if block to check if I'm doing something wrong in the query part but the program is retrieving the pass and username from the database correctly and entering the right code block but unable to redirect, see if you can help ;)




Aucun commentaire:

Enregistrer un commentaire