mercredi 17 janvier 2018

Why http.Server.Handler is an interface not a function?

I know that is a question to the author of the package, but does it have any advantages?

It would be possible to have Handler of type http.HandlerFunc and it would have couple of benefits

  • we could not wrap nearly all handlers and middlewares by http.HandleFunc
  • when we need an object with some data we could use some bound method
  • we could have more than one handler in object (without wrapping by http.HandleFunc)

An implementation of bound method is easy (whole example http://ift.tt/2mOSqKG):

type MyStruct struct {
    ctx string
}

func (m *MyStruct) handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "handler of %s was called\n", m.ctx)
}

Aucun commentaire:

Enregistrer un commentaire