I'm having some problems understanding routing rules from the standard GO library http://godoc.org/net/http#ServeMux. Matching pattern "/about" does "GET /about" but does not update the browser with the new html. The html remains the same as for "GET /". I have tried changing the patterns to "/about/" but has the unexpected effect of the submitted form generating a "GET /form" instead of a "POST /form". The code below should make this question clearer. Is this normal behaviour?
Here is a screen capture [https://www.youtube.com/watch?v=ucu5pIm3NL4] showing this behaviour.
I'm using Go 1.8.3 on Windows 10. The behaviour is the same in Google Chrome and Firefox.
I also tried Go 1.7.6, but the behaviour was the same.
Thanks for your help.
package main
import (
"net/http"
"io"
"fmt"
)
func main() {
// These 3 lines are what I expect to work, but it has a problem
http.HandleFunc("/", index) // does GET /
http.HandleFunc("/about", about) // does GET /about. URL in address
// bar changes to
// http://localhost:8080/about/,
// but html does not change.
// The html code for INDEX remains
// in browser
http.HandleFunc("/form", form) // does GET /form and included form
// does POST /form
//http.HandleFunc("/", index) // does GET /
//http.HandleFunc("/about/", about) // does GET /about
//http.HandleFunc("/form/", form) // does GET /form and included form
// also does GET /form. Does not
// do POST /form
// This code works as expected
//http.HandleFunc("/", index) // does GET /
//http.HandleFunc("/about/", about) // does GET /about
//http.HandleFunc("/form", form) // does GET /form and included form
// does /POST form as expected
http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, req *http.Request) {
fmt.Println(req.Method + req.URL.Path)
io.WriteString(w, `<html><head></head>
<body>INDEX
<a href="/">INDEX</a>
<a href="/about">ABOUT</a>
<a href="/form">FORM</a>
</body></html>
`)
}
func about(w http.ResponseWriter, req *http.Request) {
fmt.Println(req.Method + req.URL.Path)
io.WriteString(w, `<html><head></head>
<body>ABOUT
<a href="/">INDEX</a>
<a href="/about">ABOUT</a>
<a href="/form">FORM</a>
</body></html>
`)
}
func form(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodPost {
fmt.Println(req.Method + req.URL.Path)
io.WriteString(w, `<html><head></head>
<body>PROCESS FORM
<a href="/">INDEX</a>
<a href="/about">ABOUT</a>
<a href="/form">FORM</a>
</body></html>
`)
return
}
fmt.Println(req.Method + req.URL.Path)
io.WriteString(w, `<html><head></head>
<body>FORM
<a href="/">INDEX</a>
<a href="/about">ABOUT</a>
<a href="/form">FORM</a>
<form method="POST" action="/form"><input type="submit"></form>
</body></html>
`)
}