Understand Handle, Handler, and HandleFunc in Go

interface voice {
sound();
}
// Bird Item
type bird struct {}
func (b *bird) sound() {
// Add media of bird voice
}
// Car Item
type car struct {}
func (c *car) sound() {
// Add media of car voice
}
// human Item
type human struct {}
func (h *human) sound() {
// Add media of human voice
}
// Create variable of interface
var v voice
v := bird object
v.sound() // Assigning bird object in interface variable
v := car object
v.sound() // Assigning car object in interface variable
v := human object
v.sound() // Assigning human object in interface variable
func getTouchedItemObject() {
// Return instance of any touched object
}
v := getTouchedItemObject();
v.sound() // it will say sound of any touched thing in the game
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
type person struct { 
name string
age int
}
// Implement handle interface
func (p *person) serveHTTP(w http.writeResponse, r *http.Request) {
// Callback of `/blogs` path
}
func main() {
var p person
mux := http.NewServeMux()
mux.handle(“/blogs”, p)
http.ListenAndServe(“:80”, mux)
}
type blog struct {}
type comment struct {}
type tag struct {}
. . .
. . .
. . .
. . .
func (b *blog) serveHTTP(w http.writeResponse, r *http.Request) {
// Callback of /blogs path
}
func (c *comment) serveHTTP(w http.writeResponse, r *http.Request) {
// Callback of / comments
}
func (t *tag) serveHTTP(w http.writeResponse, r *http.Request) {
// Callback of /tag path
}
. . .
. . .
. . .
. . .
func main() {
var t tag
var b blog
var c comment
. . .
. . .
. . .
mux := http.NewServeMux()
mux.handle(“/blogs”, b)
mux.handle(“/comments”, c)
mux.handle(“/tags”, t)
. . .
. . .
. . .
. . .
http.ListenAndServe(“:80”, mux)
}
type HandlerFunc func(ResponseWriter, *Request) // ServeHTTP calls f(w, r).func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { 
f(w, r)
}
func getBlogs(w ResponseWriter, r *Request) {
// Callback of `/blogs` route
}
func main() {
var b blog
mux := http.NewServeMux()
mux.handleFunc(“/blogs”, “getBlogs”)
http.ListenAndServe(“:80”, mux)
}

Love to write code and discuss technology | If you explain others is simple words it means you know it very well

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store