I needed an HTTP router "violetear" that could support static and dynamic routing, with this I mean, been available to handle request like:
/read/book/:uuid/:uuid/
:uuid is something like C6FF0F6F-A274-48F4-B219-6595DCB989A5
Or basic routes like:
/read/page/3
For the middleware I used Alice which helped me to keep things compatible with the http.Handler interface.
So far so good, until the point where I needed to exchange data between the middleware or to access named parameters, like :uuid
in previous example.
Since the router was used in other projects I wanted to continue keeping compatibility with the http.Handler interface, therefore I decided not to pass the net/context
as an argument between middleware and opted to included in the http.ResponseWriter like specified here: https://github.com/nbari/violetear/blob/master/response_writer.go#L14.
With this approach basically If I need to use the context I have to do something like:
func handleUUID(w http.ResponseWriter, r *http.Request) {
cw := w.(*ResponseWriter)
// add a key-value pair to the context
cw.Set("key", "my-value")
// print current value for :uuid
fmt.Fprintf(w, "Named parameter:, %q", cw.Get(":uuid"))
}
Notice the cw := w.(*ResponseWriter)
.
This is working but wondering if there is any issue by doing the type
switch or if there are any concerns by doing this.
Thanks in advance.