Skip to content

API_handler_v1

Robert Zaremba edited this page Mar 6, 2013 · 1 revision

Requirements:

  • Handlers need to be aware about Application and Context (like model, database etc...)
  • Handlers need to be easy to pass to the Router
  • easy to extend

The Go way

The first observation is the http.ServerHTTP interface:

ServeHTTP(w ResponseWriter, r *Request)

// using:

type Counter struct {
    n int
}
func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    ctr.n++
    fmt.Fprintf(w, "counter = %d\n", ctr.n)
}
ctr := new(Counter)
http.Handle("/counter", ctr)

Adding Context with methods

type Handler1 struct {
	app      *App
	Response http.ResponseWriter
	Request  *http.Request
	Data     map[interface{}]interface{} // data for template
	Params   map[string]string           // params form request (GET, POST)
	finished bool
}

type Index Handler1
func (this *Handler1) ServeHTTP() {
}

...

app.Handle("/index", Index)

We moved the request / response objects to Handler structure to allow access for them with other wrapper methods.

More robust

type Handler2 struct {
	Handler1
Clone this wiki locally