Common function to serve data source and resource


Apologies if this is a dumb question, I am new to Go and still learning.

While adding a data source and resource for the same upstream object, I find myself duplicating a lot of code in the Read functions. I am trying to simplify this by creating a common function to retrieve and parse the data from the upstream API into a common pre-schema, applicable to both resource types, to then be used for either the data source or resource.

// Read refreshes the Terraform state with the latest data
func (d *configDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
	// read Terraform configuration data into the model
	var state configDataModel


// Read refreshes the Terraform state with the latest data
func (r *configResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// get current state
	var state configResourceModel

The problem is my common function can only reference one of the object instances, either configDataSource or configResource, so it has access to the upstream API methods:

func (d *configDataSource) ReadConfig(ctx context.Context) (configModel, diag.Diagnostics, error) {
	// initialize variables
	var config configModel

	filteringConfig, err := d.api.GetMyStuff(id)

What is the appropriate way to have my function accessible within the Read functions for both the configDataSource and configResource instances?

Thank you

Can you not just write your common function so that it does not reference either configDataSource or configResource?

What upstream API methods do you think you need within it?

I use the same model object for both DataSource and Resource roles. Those model structs usually have a method like loadApiData(ctx context.Context, in *ApiData, diags *diag.Diagnostics).

The loadApiData() method is used in both Read() methods, and sometimes in Create() and Update() as well, when those methods rely on API-server assigned values for some Computed attributes.

Thanks for the response. I need to access the upstream API to retrieve the data referenced in the HCL for the data source/resource, and set the state.

I don’t know how to access the methods I have on the upstream API without using the existing data source/resource implementations… would love to learn how to do it.

Thanks for the response.

That seems to be inline with what I am looking for. I will try to find some of your providers and look for examples in the code.