I'm implementing a simple router in Go. I used to have a lot of redundant code for each endpoint returning an error when the method called wasn't implemented for that endpoint. I refactored and made a "base" type which provides default functions for each request type that simply return the unimplemented error. Now all I have to do is override the specific method functions for a given endpoint I wish to implement. This was all fun and games until I wanted to figure out, given an endpoint variable, which of the methods have been overridden?
Omitting extraneous details, here's as simple of an example as I can think of right now:
package main
import (
"fmt"
)
// Route defines the HTTP method handlers.
type Route interface {
Get() string
Post() string
}
// BaseRoute is the "fallback" handlers,
// if those handlers aren't defined later.
type BaseRoute struct{}
func (BaseRoute) Get() string {
return "base get"
}
func (BaseRoute) Post() string {
return "base post"
}
// Endpoint holds a route for handling the HTTP request,
// and some other metadata related to that request.
type Endpoint struct {
BaseRoute
URI string
}
// myEndpoint is an example endpoint implementation
// which only implements a GET request.
type myEndpoint Endpoint
func (myEndpoint) Get() string {
return "myEndpoint get"
}
func main() {
myEndpointInstance := myEndpoint{URI: "/myEndpoint"}
fmt.Println(myEndpointInstance.URI)
fmt.Println(myEndpointInstance.Get())
fmt.Println(myEndpointInstance.Post())
}
This snippet will print out the following:
/myEndpoint
myEndpoint get
base post
So my overriding of the functions works as intended. Now I'm wondering that in my main function, after I declare the myEndpointInstance, can I tell somehow that the Post function has not been overridden and is still implemented by the underlying BaseRoute without actually calling the function? Ideally, I want something like this:
func main() {
myEndpointInstance := myEndpoint{URI: "/myEndpoint"}
if myEndpointInstace.Post != BaseRoute.Post {
// do something
}
}
I've played around with the reflect package a bit, but haven't found anything helpful.