This question already has an answer here:
I build a very simple web sever with golang to understand the http package, but I find the HandleFunc function executed two times for one request, and there's a favicon.ico I have not expected.
Here's the web server code:
package main
import (
"fmt"
"log"
"net/http"
"strings"
)
// sayHelloName a basic web function
func sayHelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() // Parse parameters
fmt.Println(r.Form)
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key", k)
fmt.Println("val", strings.Join(v, ""))
}
fmt.Fprintf(w, "hello Go-web")
}
func main() {
http.HandleFunc("/", sayHelloName)
// log.Println("Serve listen at http://localhost:8900/")
err := http.ListenAndServe(":8900", nil)
if err != nil {
log.Fatal("Listen & Serve Error", err)
}
}
http://localhost:9090/?url_long=111&url_long=222
Real Output
map[url_long:[111 222]]
path /
scheme
[111 222]
key url_long
val 111222
map[]
path /favicon.ico
scheme
[]
I don't understand why there's a favicon.ico here.
Any help will be appreciated.
</div>
The /favicon.ico
is actually requested by your browser. If you run a curl
request from shell you won't see two HandleFunc requests.
curl http://localhost:9090/?url_long=111&url_long=222
If you want to handle the /favicon.ico
path you can do something like this:
func faviconPath(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "path/to/favicon.ico")
}
func main() {
http.HandleFunc("/favicon.ico", faviconPath)
}