0

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 ?

Moss
  • 378
  • 7
  • 18
  • You need to set `myService.App` somewhere - right now in `main` you're just calling `new(MyService)` rather than calling `NewMyService` or populating the `App` field. – Adrian Feb 27 '23 at 16:25
  • I know that but I have no solution ! could you tell me how ? – Moss Feb 27 '23 at 16:38
  • There's not enough context to answer that. You said you're already able to get the app and DB layers working, which means somewhere you have a working `App` you can pass to `NewMyService`, so do that. – Adrian Feb 27 '23 at 18:16

1 Answers1

1

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)
Moss
  • 378
  • 7
  • 18