How can fix Simple Problem in redirect?

Hi there

where is my mistake in below?
POST http://localhost:5050/main?user_id=10&pw=abcd
https://play.golang.org/p/ZKTe54RQ6wQ

Any help will be appreciated,
Thanks in advance.

go http.ListenAndServe(":5050",http.HandlerFunc(redirect))

should be

http.ListenAndServe(":5050", nil)

nil means use the default multiplexer and if you start this as it’s own goroutine will the program just continue and exit. But you want ListenAndServe to “indefinitly” and listen to new connections.

thanks, Johan, actually I want to redirect HTTP to https, Here we going to assume 8080 is https :

go http.ListenAndServe(“:5050”,http.HandlerFunc(redirect))
err:= http.ListenAndServeTLS(“:8080”,“cert.pem”,“key.pem”,nil)
if err != nil {
fmt.Println(“main.go”, 23, err)
}

H. Sorry. Me reading a bit too fast. You could do like this Run multi web servers on one pysical server or vps to have to different servermux’s or use the default for https and just a new one for http with only one redirect method.

package main

import (
	"io"
	"net/http"
)

func index1(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "Hello from server 1")
}

func index2(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "Hello from server 2")
}

func main() {

	mux := http.NewServeMux()
	mux.HandleFunc("/", index1)

	http.HandleFunc("/", index2)

	go http.ListenAndServe("localhost:8001", mux)

	http.ListenAndServe("localhost:8002", nil)
}
1 Like

thanks Johan,u solved my problem and saved my day :slight_smile:

1 Like

Nice I could help you

There are a couple of mistakes that need to be addressed.
In the indexHandler function, the redirect should use http.StatusSeeOther instead of http.StatusFound to indicate a temporary redirect.

func indexHandler(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/main?user_id=10&pw=abcd", http.StatusSeeOther)
}

In the mainHandler function, the form values are accessed incorrectly. Use r.FormValue instead of r.URL.Query().Get to retrieve the form values.


func mainHandler(w http.ResponseWriter, r *http.Request) {
	userID := r.FormValue("user_id")
	password := r.FormValue("pw")
	fmt.Printf("user_id: %s, pw: %s\n", userID, password)
}

With these changes, the redirect should work correctly,
Here is one pro tips if you want deep dive how your url is redirecting check this tool https://redirectchecker.com/ you can set your login-password and check how well your application redirecting.