http.Redirect doesn't redirect anywhere

Hi there, I’m struggling to work out why the following code doesn’t seem to work:

func FormHandler(w http.ResponseWriter, r *http.Request) {

	switch r.Method {

	case "POST":
		uname := r.FormValue("uname")
		pwd := r.FormValue("pwd")

		if uname == "admin" && pwd == "root" {
			http.Redirect(w, r, "https://www.google.com", http.StatusFound)
		} else {
			http.Redirect(w, r, "https://wikipedia.com", http.StatusFound)
		}

	case "GET":
		p := ("./website/portal.html")
		http.ServeFile(w, r, p)
	}
}

(links to wikipedia and google are just for testing purposes)

Here is the relevant html form:

          <form method="post">
            <label for="uname">Username</label><br>
            <input type="text" id="uname" name="uname"><br>
            <label for="pwd">Password</label><br>
            <input type="password" id="pwd" name="pwd">
            <input type="submit" value="Log in">
          </form>

The GET method works fine and I can’t think of what the problem could be, any help would be much appreciated. Thanks for reading.

I think you miss ParseForm before reading the form values:

r.ParseForm()
uname := r.FormValue("uname")
pwd := r.FormValue("pwd")

Hi there thanks for the quick reply. I added the ParseForm line but it still didn’t work. Any other ideas would be very appreciated thanks.

I think your form is missing an action:

<form method="post" action="/path/to/action">

Ahh yes I see now, I wasn’t sure where to send the form data though, as depending on the content it would redirect to one or the other website

I think you have to rethink this a little bit :).

I tested your code like this and it works for me:

package main

import "net/http"

func FormHandler(w http.ResponseWriter, r *http.Request) {

	switch r.Method {

	case "POST":
		uname := r.FormValue("uname")
		pwd := r.FormValue("pwd")

		if uname == "admin" && pwd == "root" {
			http.Redirect(w, r, "https://www.google.com", http.StatusFound)
		} else {
			http.Redirect(w, r, "https://wikipedia.com", http.StatusFound)
		}

	case "GET":
		p := ("./website/portal.html")
		http.ServeFile(w, r, p)
	}
}

func main() {
	http.HandleFunc("/", FormHandler)

	http.ListenAndServe(":8080", nil)
}

portal.html

<h1>Hello from portal.html</h1>

<form method="post" action="/">
  <label for="uname">Username</label><br>
  <input type="text" id="uname" name="uname"><br>
  <label for="pwd">Password</label><br>
  <input type="password" id="pwd" name="pwd">
  <input type="submit" value="Log in">
</form>

I hope this helps :sweat_smile:.

Thank you so much, this did indeed help! :smiley:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.