by 0xfaded · 13y ago · 0 comments
Shameless plug: for my own use I wrote https://github.com/0xfaded/rhttp which is used with (not a thin layer over) net/http. There is a draftish blog post to go with this http://blog.0xfaded.com/.
As a side note, I use an unusal pattern of passing an empty struct as a function arguement for the sole purpose of being inspected using reflection. Undecided if this is good or bad. Thoughts?
Then a handler function could look like this:
func Do(w http.ResponseWriter, r *http.Request, params *DoParams) {
w.Write([]byte(params.Var))
}
No need for any dynamic type coercion - it can all be checked up front when the handlers are registered. The down side is that the signature of Handle would become more opaque (its argument would just be an interface{}) and you'd probably want to lose the Handler type.FWIW, passing an empty struct for the sole purpose of being inspected using reflection is not unusual (see for example gob.Register).
handle(..., User(F))
The prototype of F and User might be func F(w http.ResponseWriter, r *http.Request, s *Session, i interface{})
func User(...type of F...) func (http.ResponeWriter, r *http.Request, i interface{})
User() would do some preprocessing on the request and produce a Session for F. The problem is that User accepts ...type of F...; although it could accept an interface (of a function) but doing everything by reflection becomes cumbersome.This is one of the things I don't like about go but really you need a type system like haskell's to achieve what I want here.
type Params interface { IsParams() }
Also, you can get away with passing a nil pointer for reflection rather than allocating a nil struct: fmt.Printf("nil pointer to DoParams: %T", (*DoParams)(nil))
fmt.Printf("pointer to nil DoParams: %T", &DoParams{})
(Which isn't going to be a source of gc pressure in this instance, but still...)