The code below comes from Todd Mcleod's Golang web-dev course. What I fail to understand - even watching his video's over and over and googling everything about methods- is the following: The method ServeHTTP is attached to type hotdog, but is never ran. Still the code inside the method (in this case Fprintln(...) is executed. (When you run this code and go to localhost:8080, it diesplays "Any code you want in this func".) Could anyone explain me why this is?
Thanks a lot!
package main
import (
"fmt"
"net/http"
)
type hotdog int
func (m hotdog) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Any code you want in this func")
}
func main() {
var d hotdog
http.ListenAndServe(":8080", d)
}
It is run. ListenAndServe
calls it for every request made to your server.
Since you passed hotdog
, which implements ServeHTTP
, as a handler, every request received will be sent to hotdog's ServeHTTP
.
this function is run when the type hotdog is used
func (m hotdog) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Any code you want in this func")
}
in the main you create variable d with the type hotdog,
then in the ListenAndServe and you tell your code to use variable d every time someone connects to your server and because d is of type hotdog your first function is run everytime someone connects
func main() {
var d hotdog
http.ListenAndServe(":8080", d)
}