0

I really don't understand this code

I think I understand how receiver work but when /foo gets requested, why that struct becomes receiver to SERVEHTTP which is never called? If this is how http works, is this typical style use of receiver?

main go

import "net/http"

type fooHandler struct {
    Message sstring
}

func (f *fooHandler) ServerHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(f.Message))
}

func main() {
    http.Handle("/foo", &fooHandler{Message: "Hello world"})
}
user3502374
  • 781
  • 1
  • 4
  • 12

1 Answers1

0

First: it should be ServeHTTP, not ServerHTTP

With ServeHTTP method, fooHandler is a struct that implements http.Handler interface. Because of this, you can pass &fooHandler to http.Handle, and when that URL is loaded, the ServeHTTP method of fooHandler will be called.

Peter
  • 29,454
  • 5
  • 48
  • 60
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59