by polymathist · 12y ago · 0 comments
type HelloResource struct {
sleepy.PostNotSupported
sleepy.PutNotSupported
sleepy.DeleteNotSupported
}
Something like this: type HelloResource struct {
sleepy.DefaultResponder
}
DefaultResponder is simply a struct which has all the methods of sleepy.PostNotSupported, sleepy.PutNotSupported, etc, and is defined: type DefaultResponder struct{}
func (DefaultResponder) Get(values url.Values) (int, interface{}) {
return 405, map[string]string{"error": "Not implemented"}
}
func (DefaultResponder) Post(values url.Values) (int, interface{}) {
return 405, map[string]string{"error": "Not implemented"}
}
func (DefaultResponder) Put(values url.Values) (int, interface{}) {
return 405, map[string]string{"error": "Not implemented"}
}
func (DefaultResponder) Delete(values url.Values) (int, interface{}) {
return 405, map[string]string{"error": "Not implemented"}
}
Now, if you want to implement resource methods, you define them on the top-level struct, like so: type HelloResource struct {
sleepy.DefaultResponder
}
def (HelloResource) Get(values url.Values) (int, interface{}) {
data := map[string]string{"hello": "world"}
return 200, data
}
So now, if you call Get on a HelloResource type, it uses the method defined on HelloResource, not the one defined on it's embedded DefaultResponder type. But if you call HelloResource.Post, it uses the method defined on DefaultResponder, i.e., it returns a 405 error. This is effectively like "overriding" in Java or other object oriented languages and saves a few lines when people are using your library.What do you think? Again, I'm really just looking for feedback here as I too am new to go. Is this something that would be considered idiomatic, or is the original solution better?
(Apologies in advance for any typos or syntax errors. Didn't check this with a compiler, but hopefully you get the idea.)
type HelloResource struct {
sleepy.Resource
}
This makes it clear that you're inheriting everything from sleepy.Resource, so you can provide reasonable implementations for all methods of resources, not just HTTP methods handlers, e.g. getBodyAsJSON(), redirect(resource), etc.Also, depending on how your mux works, you could store app-level data in sleepy.Resource, to be accessed by all resources:
sleepy.Resource.DB
sleepy.Resource.Session
sleepy.Resource.Root
and other things I can't think of right now.