Hi all,
I need some guidance whether what I want to do is somehow possible in Go. I've already searched answers for two days. My problem boils down to how to sneak more in a type without changing the type.
Lets say I have to implement the following method:
func (s *server) Get(ctx context.Context, request *generated.Request) (*generated.Response, error) {
var response generated.Request
return &response, nil
}
In this case it is a zero value (nil) that will be returned for response but that is not the problem - I am just marking the types
I want to return a response that somehow implements a wider interface than generated.Response
Since that object is generated source, I cannot change it or add methods to it, however I can do the following:
// Declare a new type that embeds the generated.Response
type EnrichedResponse generated.Response
// Add a method that depends only on r
func (r *EnrichedResponse) Enriched() int {
return r.foo + 42
}
// Return the enriched response
func (h *handler) Get(ctx context.Context, request *generated.Request) (*generated.Response, error) {
var enriched EnrichedResponse
response := generated.Response(enriched)
return &response, nil
}
My problem is the Enriched() method - it can only use the state available in the initial generated.Response and I need more in order to implement the functionality.
I cannot just make EnrichedResponse a struct embedding generated.Response and add more state because then I cannot do the conversion from normal response to enriched.
So here is my question - is there any way to have this state somewhere so that the Enriched() method does not take more arguments but can be called directly.
A method declaration in Go is quite static. Additional state can be kept in some kind of closure but then I have no idea how to glue that closure to the method.
Is there any trick I am missing?
-----
Why would I want to do this? What am I trying to achieve?
Basically there is a lot of generated code and I want to keep compatibility with it.
Similar to the way Go embeds wider interfaces into narrower ones I want to be able to add methods to the generated code without having to change it.
Then - whenever some code calls the Get method on the server - based on the whether the returned value implements the Enriched interface or not and the value it returns - I can dispatch behavior.
Kind regards:
al_shopov