Search code examples
gorpc

Golang RPC and dependencies


I have two golang backends, which each has its own layers as following:

  • API layer
  • Service layer
  • Data layer

I am enjecting the app dependencies like db connection to the data layer, and constructing the layers from API to service then data. so when the app starts I will enject the app struct which is contain all depencies for runtime including db connection. everything works as expected.

but for the new feature I need to implement RPC server on first backend and RPC client on the second one.

//app.go
package app 

type App struct {
    dbconn *redis.Client
}


//main.go
package main

func main() {
    myService := new(service.MyService)
    err := rpc.Register(myService)
    .
    .
    .
}

Now in one backend I have rpc server running and i have the following method:

// myservice.go go
package service

type MyService struct {
    App: app
}

type NewMyService(app App) MyService {
    return MyService { App: app }
}


func (s MyService) getData() {
    s.app.dbconn.Get(....)
    fmt.Println(app) // 0xc0005229e0
}


func (s MyService) GetDataForExternalRequests(key string, res *string) {
    // now here I don't have access to s.app.dbconnection (it is nil)
    fmt.Println(app) // <nil>
}

in the GetDataForExternalRequests How can I access the app object ?


Solution

  • Actually I figured out, in main.go when I am creating myService I shouldn'nt use new keyword or if I used it then Ihave to constructed first then I can register it so:

    • solution 1:
    myService := service.MyService
    err := rpc.Register(myService)
    
    • solution 2:
    myService := service.NewMyService(app)
    err := rpc.Register(myService)