Closed nathanprayzo closed 9 years ago
Those sound good to me
Another option is to have one method, ReadingHandler
and then inside of it switch on if the http method is POST (and call db.AddReading) or GET (and call db.GetReadings).
Any notable pros or cons to these two approaches?
DELETE
or other http verbs for the readings since it's just another switch case (not likely for a readng, but a good pattern to follow for other resources such as devices or users).Good insights and overall I agree; let's move forward with the single http handler for all reading operations.
After attempting to implement this, I think it may be better to have separate handlers for each request.Method. I'd like to show you the code but since it's not fully functional i'm hesitant to formally push it up.
The primary source of pain with implementing the single handler for readings, is that our previous method: func getReadings(mgr db.Manager) func(w http.ResponseWriter, r http.Request) { return func(w http.ResponseWriter, r http.Request) { // Content for getReadings handler }
Doesn't have access to the http.Request, so if we try to do something like this:
r.HandleFunc("/devices/{id}/readings", ReadingHandler(mgr))
func ReadingHandler(mgr db.Manager) func(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": // function for getReadings case "POST": // function for addReadings } This results in the compiler correctly throwing the error "undefined r"
The solution appeared to be: r.HandleFunc("/devices/{id}/readings", func(w http.ResponseWriter, r *http.Request) { ReadingHandler(w, r, mgr) })
This did allow ReadingHandler to correctly switch on r.Method and compiled fine, but I couldn't get the application to return any data even though the switch for "GET" was simply returning the func for our previous getReadings.
Gotcha, looks like it may be more trouble than it's worth right now then.
To avoid confusion, the names of getReadings and addReading should be changed in main.go
Possible new names: getReadingsHandle addReadingsHandle
@crakalakin: Any suggestions for new function names?