Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine two interfaces and use it

I am new to Go, I am trying to split my code into multiple files.

So I created ServiceHTTPHandlers which has two interfaces in it

type ServiceHTTPHandlers interface {
    controller.JobHTTPHandlers
    controller.VersionHTTPHandlers
}

Here the definition

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type VersionHTTPHandlers interface {
    GetVersions(ctx *gin.Context)
}

type JobHTTPHandlers interface {
    GetJobs(ctx *gin.Context)
}

It compiles, however, I do not know how to pass two arguments to the interface parameter

func (s *Server) RegisterRoutes(h ServiceHTTPHandlers) {
    var router = s.router

    router.GET("/jobs", h.GetJobs)
    router.GET("/versions", h.GetVersions)
}

main.go

jobs := controller.JobService{}
versions := controller.VersionService{}

svr.RegisterRoutes(&jobs, &versions) // HERE

Is it possible to pass two or more interfaces to a single one?

I tried svr.RegisterRoutes(&{jobs, versions}) however I have not luck

>Solution :

Define a struct type with an anonymous field for each interface. Initialize the struct with the controllers:

h := struct {
    VersionHTTPHandlers
    JobHTTPHandlers
}{
    controllers.VersionService{},
    controllers.JobService{},
}
svr.RegisterRoutes(h)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading